When performing a division operation using Java's BigDecimal class, you may encounter the following exception:
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
This error occurs when the division operation results in a decimal quotient with an infinitely long expansion. By default, BigDecimal operations are exact, meaning they produce the exact mathematical result without rounding.
However, the divide method throws an ArithmeticException when the result has a non-terminating decimal expansion and an exact result is expected (i.e., when the precision setting of the MathContext object used is 0).
To resolve this issue, you can specify a non-zero precision setting for the MathContext object. This will force the result to be rounded to a specified number of decimal places:
a.divide(b, 2, RoundingMode.HALF_UP)
In this case, 2 is the scale (number of decimal places), and RoundingMode.HALF_UP is the rounding mode to use. By specifying a precision, you can obtain a finite and representable decimal result.
以上がJava の BigDecimal が非終了 10 進数展開に対して ArithmeticException をスローするのはなぜですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。