ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result”

1.5K    Asked by AdityaYadav in Java , Asked on Jun 6, 2021

Why does the following code raise the exception shown below?

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.
Answered by alex Duncan

To solve non terminating decimal expansion no exact representable decimal result error, you can go through my answer:


When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as they are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases before 5.)

As a corollary of computing the exact outcome, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of the divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.

If the quotient has a non terminating 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.

To solve non terminating decimal expansion no exact representable decimal result, you need to try something like this:

a.divide(b, 2, RoundingMode.HALF_UP)

where 2 is precision and RoundingMode.HALF_UP is rounding mode

Hope this helps!



Your Answer

Interviews

Parent Categories