除法運算時的一個常見錯誤之Non-terminating decimal expansion

1、背景

今天在計算庫存消耗百分比(消耗的庫存/總庫存)的時候遇到了一個錯誤,java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.java

經過異常的描述,咱們知道這是由於,某些場景下對於如1/3會獲得一個無窮小數,這個時候須要定義計算結果要保留到小數點後幾位,不然就會拋出上面的異常。ide

2、方法介紹

出現異常時使用的方法,此方法沒有精度設置。spa

public BigDecimal divide(BigDecimal divisor) 
複製代碼

在進行除法運算的時候,咱們須要使用下面的方法來進行精度控制。code

public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
複製代碼

附:不要忘記判斷分母是否爲0  ci

3、代碼以下

BigDecimal b1 = new BigDecimal(1);
BigDecimal b2 = new BigDecimal(3);
if (!Objects.equals(b2, BigDecimal.ZERO)) {
    // 不能整除,數學上是無窮小數,拋出ArithmeticException異常
    //BigDecimal b3 = b1.divide(b2);
    // 指定計算結果的精度,保留到小數點後幾位,以及舍入模式
    BigDecimal b3 = b1.divide(b2, 4, BigDecimal.ROUND_HALF_UP);
    System.out.println(b3.toEngineeringString());
}
複製代碼
相關文章
相關標籤/搜索