首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 數學運算:向上取整 Math.ceil 與向下取整 Math.floor 完全指南

     編輯:Java 綜合教學

核心方法

方法含義返回類型示例
Math.ceil(double a)向上取整(≥ 參數的最小整數)doubleceil(1.2) → 2.0; ceil(-1.2) → -1.0
Math.floor(double a)向下取整(≤ 參數的最大整數)doublefloor(1.8) → 1.0; floor(-1.8) → -2.0
Math.round(double a)四捨五入(最接近的 long)longround(1.5) → 2; round(-1.5) → -1
Math.rint(double a)銀行家舍入(.5 向偶數)doublerint(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
    }
}

常見陷阱與注意事項

  1. 返回值是 double/long,非 int,賦值給 int 需強轉:(int) Math.ceil(x)。
  2. 負數語義:ceil(-1.2) = -1(向正無窮大),floor(-1.2) = -2(向負無窮大)。
  3. 整數除法:int / int 先截斷再轉 double,須先轉型:(double)a / b。
  4. 精度問題:浮點數二進制表示不精確,金融計算請用 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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved