问题描述
为什么以下代码会引发如下所示的异常?
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.
推荐答案
From the Java 11 BigDecimal
docs:
当为 MathContext
对象提供精度设置为 0 时(例如,MathContext.UNLIMITED
),算术运算是精确的,算术方法也是不带 MathContext
对象.(这是 5 之前的版本中唯一支持的行为.)
作为计算精确结果的必然结果,精度设置为 0 的 MathContext
对象的舍入模式设置未使用,因此无关紧要.在除法的情况下,精确的商可以有无限长的十进制展开;例如,1 除以 3.
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.
如果商有一个非终止的十进制扩展并且指定操作返回一个精确的结果,则抛出一个ArithmeticException
.否则,将返回除法的确切结果,就像其他操作一样.
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.
要修复,您需要执行以下操作:
a.divide(b, 2, RoundingMode.HALF_UP)
其中 2 是比例,RoundingMode.HALF_UP 是四舍五入模式
where 2 is the scale and RoundingMode.HALF_UP is rounding mode
有关详细信息,请参阅此博文.
For more details see this blog post.
这篇关于ArithmeticException:“非终止十进制扩展;没有精确的可表示的十进制结果"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!