Divide Error for BigDecimal_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Divide Error for BigDecimal

Divide Error for BigDecimal

 2018/6/4 12:12:05  jz_2017  程序员俱乐部  我要评论(0)
  • 摘要:java.lang.ArithmeticException:Non-terminatingdecimalexpansion;noexactrepresentabledecimalresult.Reference:https://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable?utm_medium=organic&
  • 标签:for ide Decimal
class="lang-java prettyprint prettyprinted">monospace, sans-serif; font-size: 13px; vertical-align: baseline; white-space: inherit;">java.lang.ArithmeticException:Non-terminating decimal expansion; no exact representable decimal result.

Reference:?https://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

?

?

From the?Java 5?docs (Java 8 docs?here):

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.)

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.

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.

To fix, you need to do something like this:

a.divide(b,2,RoundingMode.HALF_UP)

where 2 is precision and RoundingMode.HALF_UP is rounding mode

发表评论
用户名: 匿名