number與string的轉換


// number -> string
// toString()
/*
var num = 10;
var res = num.toString();
alert(typeof (num));
alert(typeof (res));
*/

// 加一個空格
/*
var num = 10;
var res = num + ""
alert(num + ", " + typeof (num));
alert(res + ", " + typeof (res));
*/

// 使用String(數字)函數
/*
var num = 10;
var res = String(num);
alert(num + ", " + typeof (num));
alert(res + ", " + typeof (res));
*/

// 沒有固定精度的表示
/*
var n = 1234.56789;
var s4 = n.toFixed(2);
var s5 = n.toExponential(2); // 指數表示
var s6 = n.toPrecision(2); // 有效位數

alert(s4 + ", " + typeof(s4));
alert(s5 + ", " + typeof(s5));
alert(s6 + ", " + typeof(s6));
*/

// string -> number
// 做除了加法以外的數字運算
/*
var s = "12345";
var r = s / 1; // s - 0;
alert(s + ", " + typeof s);
alert(r + ", " + typeof r);
*/

// 使用parse系方法
// parseInt() parseFloat()
/*
var s = "08";
var r = parseInt(s);
alert(s + ", " + typeof s);
alert(r + ", " + typeof r);
*/
// parse系方法,只識別一個字符串中開始的數字,如果識別不了就返回NaN
alert(parseInt("a123abc") + 1);

// 使用Number()函數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM