java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result exception solution
Scenario description
Today when writing a JAVA program an exception occurred: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal expansion decimal result.
The statement that found the error was:
foo.divide(bar));
Solution
It turns out that if you use BigDecimal to divide in JAVA, you must pass the second parameter in the divide method, and the definition is accurate to a few decimal places. Otherwise, if the result is an infinite loop decimal, it will be thrown. The above exception occurred.
foo.divide(bar, 2, BigDecimal.ROUND_HALF_UP);
Source code
Note that the divide method of BigDecimal has two overloaded methods, one is to pass two parameters, the other is to pass three parameters:
Two-parameter method:
@param divisor value by which this {
@code BigDecimal} is to be divided. 传入除数
@param roundingMode rounding mode to apply. 传入round的模式
Three parameter method:
@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的模式