Java java.lang.Math 提供了三個常用的取整方法:floor(向下取整)、round(四捨五入)、ceil(向上取整)。它們對正負數的處理邏輯不同,開發中常因混淆導致 Bug。本文通過定義、對比表、實測代碼全方位解析,助你徹底掌握。
(long)Math.floor(a + 0.5),返回 long;float 版返回 int| 輸入 | floor | round | ceil |
|---|---|---|---|
| 1.4 | 1.0 | 1 | 2.0 |
| 1.5 | 1.0 | 2 | 2.0 |
| 1.6 | 1.0 | 2 | 2.0 |
| -1.4 | -2.0 | -1 | -1.0 |
| -1.5 | -2.0 | -1 | -1.0 |
| -1.6 | -2.0 | -2 | -1.0 |
關鍵觀察:
floor 永遠向更小方向:-1.4 → -2,-1.6 → -2ceil 永遠向更大方向:-1.4 → -1,-1.6 → -1round 正數四捨五入,負數「向零偏移」:-1.5 → -1(而非 -2),因 floor(-1.5 + 0.5) = floor(-1.0) = -1public class MathRoundTest {
public static void main(String[] args) {
double[] nums = {1.4, 1.5, 1.6, -1.4, -1.5, -1.6};
for (double n : nums) test(n);
}
private static void test(double n) {
System.out.printf("Math.floor(%.1f)=%.1f%n", n, Math.floor(n));
System.out.printf("Math.round(%.1f)=%d%n", n, Math.round(n));
System.out.printf("Math.ceil(%.1f)=%.1f%n", n, Math.ceil(n));
System.out.println("---");
}
}
floor/ceil:返回 double(如 1.0、-2.0)round(double):返回 longround(float):返回 int若需 int,可強轉:(int)Math.round(d),注意溢出風險。
floor(x + 0.5) 即可推導。2.675 可能因二進制表示誤差導致 round 結果不符預期。金融計算請用 BigDecimal.setScale(RoundingMode.HALF_UP)。下次遇到取整需求,先問自己:要向下、向上、還是四捨五入?負數怎麼處理? 對號入座,零失誤。