Home >Java >javaTutorial >Why Does Dividing BigDecimals Without a MathContext Result in a 'Non-terminating Decimal Expansion' Exception?
Non-Terminating Decimal Expansion Exception in Division of BigDecimals
When dividing two BigDecimal objects without specifying a MathContext, the operation can result in an "ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result" exception.
This is because the quotient of certain divisions (like 1 divided by 3) has an infinitely long decimal expansion. When the precision is set to 0 (the default), the exact result must be computed. If the quotient has a non-terminating expansion, an exception is thrown.
Solution
To fix this, a MathContext with a specific scale and rounding mode must be provided. The following code demonstrates this:
a.divide(b, 2, RoundingMode.HALF_UP)
In this example, the scale is set to 2, and the rounding mode is set to RoundingMode.HALF_UP. This ensures that the division result is rounded to a specific scale and that the exception is avoided.
For more in-depth information, refer to the Java 11 BigDecimal documentation or external resources like this blog post.
The above is the detailed content of Why Does Dividing BigDecimals Without a MathContext Result in a 'Non-terminating Decimal Expansion' Exception?. For more information, please follow other related articles on the PHP Chinese website!