js中Math.round、parseInt、Math.floor和Math.ceil小數取整小結


以前經常在代碼中看到Math.round、parseInt、Math.floor和Math.ceil這四個函數,雖然知道結果都可以返回一個整數,但是對他們四者的區別還是不太清楚,今天就做一個小結。

一、Math.round

作用:四舍五入,返回參數+0.5后,向下取整。

如:

Math.round(5.57)  //返回6

Math.round(2.4)   //返回2

Math.round(-1.5)  //返回-1

Math.round(-5.8)  //返回-6

二、parseInt

作用:解析一個字符串,並返回一個整數,這里可以簡單理解成返回舍去參數的小數部分后的整數。

如:

parseInt(5.57)  //返回5

parseInt(2.4)  //返回2

parseInt(-1.5)  //返回-1

parseInt(-5.8)  //返回-5

三、Math.floor

作用:返回小於等於參數的最大整數。

如:

Math.floor(5.57)  //返回5

Math.floor(2.4)  //返回2

Math.floor(-1.5)  //返回-2

Math.floor(-5.8)  //返回-6

四、Math.ceil

作用:返回大於等於參數的最小整數

Math.ceil(5.57)  //返回6

Math.ceil(2.4)  //返回3

Math.ceil(-1.5)  //返回-1

Math.ceil(-5.8)  //返回-5

 


免責聲明!

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



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