为什么下面的代码会引发如下所示的异常?
BigDecimal a = new BigDecimal("1.6");
BigDecimal b = new BigDecimal("9.2");
a.divide(b) // results in the following exception.
例外:
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
来自Java 11 BigDecimal文档:
When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)
As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.
If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.
要修复,你需要做这样的事情:
a.divide(b, 2, RoundingMode.HALF_UP)
其中2是比例和round mode。HALF_UP是舍入模式
欲了解更多细节,请参阅这篇博客文章。