ArithmeticException:“非终止十进制扩展;没有精确的可表示的十进制结果" [英] ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

查看:32
本文介绍了ArithmeticException:“非终止十进制扩展;没有精确的可表示的十进制结果"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码会引发如下所示的异常?

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.

推荐答案

来自 Java 11 BigDecimal 文档:

From the Java 11 BigDecimal docs:

当为 MathContext 对象提供精度设置为 0 时(例如,MathContext.UNLIMITED),算术运算是精确的,算术方法也是不带 MathContext 对象.(这是 5 之前的版本中唯一支持的行为.)

When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 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:“非终止十进制扩展;没有精确的可表示的十进制结果"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆