Today, when writing a Java program, an exception occurred: java.lang.arithmeticexception:non-terminating decimal expansion; No exact representable decimal result.
The statement that found the error is:
Originally in Java If you use BigDecimal to do division in the divide method must pass the second parameter, the definition of the number of decimal points, otherwise, in the case of not divisible, the result is an infinite loop decimal, the above exception will be thrown.
Workaround:
1 |
foo.divide(bar, 2 , BigDecimal.ROUND_HALF_UP); |
Note that this divide method has two overloaded methods, one for two parameters and one for three parameters:
Two parameters of the method:
@param divisor value by which this {@code BigDecimal} are to be divided. Incoming divisor
@param roundingmode rounding mode to apply. Mode of incoming round
Three parameters of the method:
@param divisor value by which this {@code BigDecimal} are to be divided. Incoming divisor
@param scale Scale of the {@code BigDecimal} quotient to be returned. Incoming precision
@param roundingmode rounding mode to apply. Mode of incoming round
java.lang.arithmeticexception:non-terminating decimal expansion; No exact representable decimal result exception workaround