核心方法
| 方法 | 含義 | 返回類型 | 示例 |
Math.ceil(double a) | 向上取整(≥ 參數的最小整數) | double | ceil(1.2) → 2.0; ceil(-1.2) → -1.0 |
Math.floor(double a) | 向下取整(≤ 參數的最大整數) | double | floor(1.8) → 1.0; floor(-1.8) → -2.0 |
Math.round(double a) | 四捨五入(最接近的 long) | long | round(1.5) → 2; round(-1.5) → -1 |
Math.rint(double a) | 銀行家舍入(.5 向偶數) | double | rint(1.5) → 2.0; rint(2.5) → 2.0 |
實戰代碼
public class RoundDemo {
public static void main(String[] args) {
double a = 35, b = 20;
double c = a / b; // 1.75
System.out.println("c = " + c);
System.out.println("ceil = " + Math.ceil(c)); // 2.0
System.out.println("floor = " + Math.floor(c)); // 1.0
System.out.println("round = " + Math.round(c)); // 2
}
}
常見陷阱與注意事項
- 返回值是 double/long,非 int,賦值給 int 需強轉:
(int) Math.ceil(x)。
- 負數語義:ceil(-1.2) = -1(向正無窮大),floor(-1.2) = -2(向負無窮大)。
- 整數除法:
int / int 先截斷再轉 double,須先轉型:(double)a / b。
- 精度問題:浮點數二進制表示不精確,金融計算請用
BigDecimal 並設 RoundingMode。
BigDecimal 精確取整範例
BigDecimal v = new BigDecimal("1.75");
BigDecimal up = v.setScale(0, RoundingMode.CEILING); // 2
BigDecimal down = v.setScale(0, RoundingMode.FLOOR); // 1
BigDecimal half = v.setScale(0, RoundingMode.HALF_UP); // 2