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

查看:218
本文介绍了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 8 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.)

作为计算确切结果的必然结果,舍入模式设置为不使用MathContext
对象,其精度设置为0,因此无关紧要。在
的除法情况下,准确的商可以有一个无限长的十进制
扩展;例如,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)

where 2 is precision and RoundingMode.HALF_UP is rounding mode

更多细节: http:// jaydeepm .wordpress.com / 2009/06/04 / bigdecimal-and-non-terminating-decimal-expansion-error /

这篇关于ArithmeticException:“非终止十进制扩展;没有确切的可表示的十进制结果“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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