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.
以上是為什麼在沒有 MathContext 的情況下除 BigDecimal 會導致「非終止十進制擴展」異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!