js轉換成數字


/**
 * 轉換成數字,有兩種方法:
 * 1.Number(var)
 * 2.parseInt(var)與parseFloat(var)
 */
// 字符串轉換成數字
// 純字母
var foo = 'hello';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): NaN
// 字母數字混合
var foo = 'hello123';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): NaN
// 純數字
var foo = '8848';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 8848
var foo = '3.14234';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 3.14234
// boolean
var foo = true;
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 1
var foo = false;
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 0
// null
var foo = null;
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 0
// undefined
var foo = undefined;
console.log(`typeof foo: ${typeof foo}, Number(foo): ${Number(foo)}`); // typeof foo: undefined, Number(foo): NaN
// 字母數字混合
// 字母在前
var foo = 'hello123';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN
// 字母在后
var foo = '123hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 123
// 穿插
var foo = '13word23hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 13
var foo = 'w13ord23hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN
// 夾帶浮點數
var foo = 'hello23.54';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN
var foo = '23.54hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 23
var foo = '0.999hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 0
var foo = 'wor0.999hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN
var foo = '070';
// parseInt默認十進制
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 70
// 八進制
console.log(`parseInt(foo, 8): ${parseInt(foo, 8)}`); // parseInt(foo): 56
// 十六進制
console.log(`parseInt(foo, 16): ${parseInt(foo, 16)}`); // parseInt(foo): 122

 


免責聲明!

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



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