js函数 Number()、parseInt()、parseFloat()的区别:
生活随笔
收集整理的這篇文章主要介紹了
js函数 Number()、parseInt()、parseFloat()的区别:
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Number()、parseInt()、parseFloat()的區別:
Number()的強制類型轉換與parseInt()和parseFloat()方法的處理方式相似,只是它轉換的是整個值,而不是部分值。parseInt()和parseFloat()方法只轉換第一個無效字符之前的字符串。如“3.4.5”被轉換成“3.4”,
用Number()進行強制類型轉換將返回NAN,
如果字符串值能被完整地轉換,Number()將判斷是調用parseInt()還是parseFloat()。
Js代碼 ?var?bb?=?"35.23ace23"; ?? document.write(Number(bb));????????????????????//NaN?? document.write(parseFloat(bb));????????????????//35.23?? document.write(parseFloat(Number(bb)));????????//NaN?? [js] view plaincopy 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() 方法可把一個數字舍入為最接近的整數。
Js代碼 ?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????
Number()的強制類型轉換與parseInt()和parseFloat()方法的處理方式相似,只是它轉換的是整個值,而不是部分值。parseInt()和parseFloat()方法只轉換第一個無效字符之前的字符串。如“3.4.5”被轉換成“3.4”,
用Number()進行強制類型轉換將返回NAN,
如果字符串值能被完整地轉換,Number()將判斷是調用parseInt()還是parseFloat()。
Js代碼 ?
Number.toFixed(x) 、 Number.toPrecision(x) 、 Math.Round(x)的區別:
Number.toFixed(x) 是將指定數字截取小數點后 x 位, Number.toPrecision(x) 是將整個數字截取指定(x)長度。
注意:一個是計算小數點后的長度,一個是計算整個數字的長度 。
Math.round() 方法可把一個數字舍入為最接近的整數。
Js代碼 ?
總結
以上是生活随笔為你收集整理的js函数 Number()、parseInt()、parseFloat()的区别:的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: web标准---html、css、js分
- 下一篇: js bool true false 真