Wednesday, 23 May 2018

[Java] java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result

ErrorCode

BigDecimal diviedeDecimal = gapDecimal.divide( new BigDecimal( D));


When use divide method, you should set rounding mode and digit. For example, a result of '10 / 3' is 3.33333.... And can't not represent digit.

From the Java 5 docs (Java 8 docs here):
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.

Soluition


BigDecimal diviedeDecimal = gapDecimal.divide( new BigDecimal( D), BigDecimal.ROUND_UP);
BigDecimal diviedeDecimal = gapDecimal.divide( new BigDecimal( D), 3, BigDecimal.ROUND_UP);



No comments:

Post a Comment