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

Java 數值截斷與四捨五入:類型轉換 vs Math.round 陷阱

     編輯:Java 相關知識

浮點數轉整數時,Java 預設行為是「截斷」(向零取整),而非四捨五入。這個細節在金融計算、邊界判斷中極易產生 Bug。本文對比兩種方式並給出最佳實踐。

1. 直接強制轉型:截斷

double d1 = 0.7, d2 = -0.7;
int i1 = (int) d1; // 0
int i2 = (int) d2; // 0(向零取整,非向下取整)

float f1 = 0.7f, f2 = -0.7f;
int j1 = (int) f1; // 0
int j2 = (int) f2; // 0

規則:丟棄小數部分,保留整數部分(正數向下、負數向上)。

2. Math.round:四捨五入

Math.round(0.7)   // 1  (long)
Math.round(0.4)   // 0
Math.round(-0.7)  // -1
Math.round(-0.4)  // 0
Math.round(0.7f)  // 1  (int)
Math.round(-0.7f) // -1
  • 返回類型:double 入參 → long;float 入參 → int。
  • 實現:(long)Math.floor(x + 0.5),即「加 0.5 後向下取整」。
  • 屬 java.lang,無需額外導入。

3. 進階:BigDecimal 精確控制

金融/科學計算需指定捨入模式與精度:

BigDecimal bd = new BigDecimal("1.555");
bd.setScale(2, RoundingMode.HALF_UP)    // 1.56
  .setScale(2, RoundingMode.HALF_EVEN)  // 1.56 (銀行家捨入)
  .setScale(2, RoundingMode.DOWN);      // 1.55 (截斷)

4. 常見陷阱對比表

輸入(int) 強轉Math.roundMath.floorMath.ceil
2.32223
2.72323
-2.3-2-2-3-2
-2.7-2-3-3-2

5. 最佳實踐建議

  • 一般業務四捨五入 → Math.round。
  • 貨幣/精度敏感 → BigDecimal + 明確 RoundingMode。
  • 分頁/索引計算需向下取整 → Math.floorDiv (JDK 8+) 或手動處理負數。
  • 避免 double 直接比較相等,用 Math.abs(a-b) < epsilon。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved