JavaScript函数 Number()、parseInt()、parseFloat()的区别

Number()、parseInt()、parseFloat()的区别: Number()的强制类型转换与parseInt()和parseFloat()方法的处理方式相似,只是它转…

Number()、parseInt()、parseFloat()的区别:

Number()的强制类型转换与parseInt()和parseFloat()方法的处理方式相似,只是它转换的是整个值,而不是部分值。parseInt()和parseFloat()方法只转换第一个无效字符之前的字符串。如“3.4.5”被转换成“3.4”,

用Number()进行强制类型转换将返回NAN,
如果字符串值能被完整地转换,Number()将判断是调用parseInt()还是parseFloat()。

1
2
3
4
var bb = “35.23ace23”;
document.write(Number(bb));                    //NaN
document.write(parseFloat(bb));                //35.23
document.write(parseFloat(Number(bb)));        //NaN  
1
2
3
4
var bb = “35.23ace23”;
document.write(Number(bb));                    //NaN
document.write(parseFloat(bb));                //35.23
document.write(parseFloat(Number(bb)));        //NaN  

Number.toFixed(x) 、 Number.toPrecision(x) 、 Math.Round(x)的区别:

Number.toFixed(x) 是将指定数字截取小数点后 x 位, Number.toPrecision(x) 是将整个数字截取指定(x)长度。
注意:一个是计算小数点后的长度,一个是计算整个数字的长度 。
Math.round() 方法可把一个数字舍入为最接近的整数。

1
2
3
4
5
6
7
8
var aa = 2.3362;
document.write(aa.toFixed(1));                 // 2.3 
document.write(aa.toFixed(2));                 // 2.34 
document.write(aa.toPrecision(2));             // 2.3
document.write(aa.toPrecision(3));             // 2.34  
document.write(Math.round(4.60));             // -5
document.write(Math.round(aa * 10) / 10);      // 2.3 
document.write(Math.round(aa * 100) / 100);    // 2.34    
本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/2772.html

为您推荐

返回顶部