Math.floor() 與 parseInt()

parseInt()與Math.floor()都能實現數字的向下取整,可是二者存在根本上的差別,
1.Math.floor()
用於一個數的向下取整,不能解析字符串
<script type="text/javascript">
document.write(Math.floor(0.89) + "<br />")  //結果0
document.write(Math.floor(-0.2) + "<br />")  //結果-1
document.write(Math.floor(-4.3) + "<br />")  //結果-5 document.write(Math.floor("3") + "<br />")  //結果3
document.write(parseInt(2*4) + "<br />")  //結果8 document.write(Math.floor("hello") + "<br />")  //結果NaN
document.write(parseInt("760px");  //結果NaN
</script>
2.parseInt()
把任意字符串轉換爲整數(必須以數字開頭)
<script type="text/javascript">
document.write(parseInt(0.89) + "<br />")  //結果0
document.write(parseInt(-0.2) + "<br />")  //結果0
document.write(parseInt(-4.3) + "<br />")  //結果-4   
document.write(parseInt("3") + "<br />")  //結果3 
document.write(parseInt(2*4) + "<br />")  //結果8
document.write(parseInt("hello") + "<br />")  //結果NaN 
document.write(parseInt("760px");  //結果760
</script>

3.parseInt(string, radix)javascript

能夠把二進制、八進制、十六進制或其餘任何進制的字符串轉換成整數,默認轉化爲十進制。java

<script type="text/javascript"> 
document.write(parseInt(
"12",10) + "<br />")  //結果12
document.write(parseInt("12",8) + "<br />")  //結果10
document.write(parseInt("12",2) + "<br />")  //結果1  
document.write(parseInt("A",10) + "<br />")  //結果NaN
document.write(parseInt("A",16) + "<br />")  //結果10
</script>

概括說明spa

1)、Math.floor對正數的小數取「舍」,對負數的小數取「入」;code

2)、praseInt屬於類型轉換,會對字符逐級判斷,佔用內存較高;blog

3)、二者的用途、用法都不相同,儘可能避免混合使用ip

相關文章
相關標籤/搜索