1. 程式人生 > >【ArithmeticException】: Non-terminating decimal expansion; no exact representable decimal result。

【ArithmeticException】: Non-terminating decimal expansion; no exact representable decimal result。

原來JAVA中如果用BigDecimal做除法的時候一定要在divide方法中傳遞第二個引數,定義精確到小數點後幾位,否則在不整除的情況下,結果是無限迴圈小數時,就會丟擲以上異常。

解決方法:

foo.divide(bar, 2, BigDecimal.ROUND_HALF_UP);
注意這個divide方法有兩個過載的方法,一個是傳兩個引數的,一個是傳三個引數的:

兩個引數的方法:

@param divisor value by which this {@code BigDecimal} is to be divided. 傳入除數

@param roundingMode rounding mode to apply. 傳入round的模式

三個引數的方法:

@param divisor value by which this {@code BigDecimal} is to be divided. 傳入除數
@param scale scale of the {@code BigDecimal} quotient to be returned. 傳入精度
@param roundingMode rounding mode to apply. 傳入round的模式