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