JavaScript 字串 數字 轉換

  • 18256
  • 0

JavaScript 字串 數字 轉換

	function wl(s){document.write((s||'')+'< br>\r\n');}

	var s="1234.567";
	var i=1234.567;
	
	wl('string to int');
	wl(parseInt(s));
	wl(parseInt(s,10));//10進位
	wl(parseInt(s,16));//16進位

	wl(parseFloat(s));
	
	wl(0+s);
	wl(0+(+s));//+1234.567 正的1234.567,隱含轉換數字
	
	wl('int to string');
	wl(i.toString());
	wl(i.toString(10));//10進位
	wl(i.toString(16));//16進位

	wl(i.toFixed(2));//四捨五入小數第二位,似乎沒有四捨六入五成雙的問題

寫個實用一點點的例子吧…色碼表:dob.tnc.edu.tw/demo.php

原程式:

document.write('<table border="0" width="100%" >');
var a,b,c,strA,strB,intF,intS;
function chgHex2(numeric) {
//chgHex2是副函數,負責更變0-15成為十六進制。而chgHex是主函數,負責把0-255轉成十六進制。
   switch(numeric) {
      case 0:  strA='0'; break;
      case 1:  strA='1'; break;
      case 2:  strA='2'; break;
      case 3:  strA='3'; break;
      case 4:  strA='4'; break;
      case 5:  strA='5'; break;
      case 6:  strA='6'; break;
      case 7:  strA='7'; break;
      case 8:  strA='8'; break;
      case 9:  strA='9'; break;
      case 10: strA='A'; break;
      case 11: strA='B'; break;
      case 12: strA='C'; break;
      case 13: strA='D'; break;
      case 14: strA='E'; break; 
      case 15: strA='F'; break;
   }
   return strA;
}
function chgHex(numeric) {
   if(numeric<10) {
       strB='0' + numeric;
   } else if (numeric<16&&numeric>9) {
       strB='0' + chgHex2(numeric);
   } else {
      intF=0; intS=0;
     while (numeric>15) {
         numeric=numeric-15;
        numeric=numeric-1;
          intF++;
      }
     intS=numeric;
      strB=chgHex2(intF) + chgHex2(parseInt(intS));
   }
   return strB;
}
a=0; b=0; c=0;
var intTmp=-1;
document.write('<tr>');
for (a=0;a<=255;a=a+15){
   for (b=0;b<=255;b=b+15) {
      for (c=0;c<=255;c=c+60) {
       intTmp++;
       if (intTmp>10) {
          document.write('</tr><tr>');
          intTmp=0;
      }
      var strH=chgHex(a) + chgHex(b) + chgHex(c)
         document.write('<td bgcolor="#'+ strH +'" style="font-family: Verdana; font-size: 10pt;">#' + strH + '</td>');
      }
   }
}
document.write('<td bgcolor="#FFFFFF" style="font-family: Verdana; font-size: 10pt;">#FFFFFF</td></tr></table>');

修改一下:

document.write('<table border="0" width="100%" >');
var a,b,c,strA,strB,intF,intS;
function chgHex(numeric) {
	var s=numeric.toString(16).toUpperCase();
	return (s.length==1 ?'0'+s :s);
}
a=0; b=0; c=0;
var intTmp=-1;
document.write('<tr>');
for (a=0;a<=255;a=a+15){
   for (b=0;b<=255;b=b+15) {
      for (c=0;c<=255;c=c+60) {
       intTmp++;
       if (intTmp>10) {
          document.write('</tr><tr>');
          intTmp=0;
      }
      var strH=chgHex(a) + chgHex(b) + chgHex(c)
         document.write('<td bgcolor="#'+ strH +'" style="font-family: Verdana; font-size: 10pt;">#' + strH + '</td>');
      }
   }
}
document.write('<td bgcolor="#FFFFFF" style="font-family: Verdana; font-size: 10pt;">#FFFFFF</td></tr></table>');

download sample