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)

可以把二進制、八進制、十六進制或其他任何進制的字符串轉換成整數,默認轉化為十進制。

<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>

歸納說明

1)、Math.floor對正數的小數取“舍”,對負數的小數取“入”;

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

3)、兩者的用途、用法都不相同,盡量避免混合使用


免責聲明!

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



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