JavaScript 中將小數捨入為整數的方法主要有三個:Math.ceil()、Math.floor() 與 Math.round()。它們各自遵循不同的捨入規則:
◎ Math.ceil() 執行無條件進位,即它總是將數值向上捨入為最接近的整數;
◎ Math.floor() 執行無條件捨去,即它總是將數值向下捨入為最接近的整數;
◎ Math.round() 執行標準四捨五入,即將數值四捨五入為最接近的整數(這也是我們在數學課上學到的規則)。
使用範例:
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 之間的數值都回傳 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