Javascript Math ceil()、floor()、round()三個函數的區別

LorMartinda 8年前發布 | 7K 次閱讀 JavaScript開發

來自: http://my.oschina.net/daniels/blog/609977


下面來介紹將小數值舍入為整數的幾個方法:Math.ceil()、Math.floor()和Math.round()。 這三個方法分別遵循下列舍入規則:
◎Math.ceil()執行向上舍入,即它總是將數值向上舍入為最接近的整數;
◎Math.floor()執行向下舍入,即它總是將數值向下舍入為最接近的整數;
◎Math.round()執行標準舍入,即它總是將數值四舍五入為最接近的整數(這也是我們在數學課上學到的舍入規則)。

下面是使用這些方法的示例:

?

1
2
3
4
5
6
7
8
9
alert(Math.ceil(25.9)); //26
alert(Math.ceil(25.5)); //26
alert(Math.ceil(25.1)); //26
alert(Math.round(25.9)); //26
alert(Math.round(25.5)); //26
alert(Math.round(25.1)); //25
alert(Math.floor(25.9)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.1)); //25

南昌網絡公司技術人員總結:對于所有介于25和26(不包括26)之間的數值,Math.ceil()始終返回26,因為它執行的是向上舍入。Math.round()方法只在數值大于等于25.5時返回26;否則返回25。最后,Math.floor()對所有介于25和26(不包括26)之間的數值都返回25。

以下是一些補充:
ceil():將小數部分一律向整數部分進位。 
如: 

Math.ceil(12.2)//返回13 
Math.ceil(12.7)//返回13 
Math.ceil(12.0)// 返回12 

floor():一律舍去,僅保留整數。 
如: 

Math.floor(12.2)// 返回12 
Math.floor(12.7)//返回12 
Math.floor(12.0)//返回12 

round():進行四舍五入 
如: 

Math.round(12.2)// 返回12 
Math.round(12.7)//返回13 
Math.round(12.0)//返回12

 

 本文由用戶 LorMartinda 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!