本文介绍了是什么原因导致“不终止的十进制扩展”? BigDecimal.divide的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前使用过BigDecimals,但不是经常使用,今天早上我在做一些事情,但不断出现以下异常:

I've used BigDecimals before but not very often and I was working on something this morning and I kept getting the following exception:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion;
no exact representable decimal result.
    at java.math.BigDecimal.divide(BigDecimal.java:1594)

尝试设置比例并使用舍入消除此类问题:

I was attempting to set the scale and use rounding to eliminate the problem like so:

    BigDecimal bd1 = new BigDecimal(1131).setScale(2,BigDecimal.ROUND_HALF_UP);
    BigDecimal bd2 = new BigDecimal(365).setScale(2,BigDecimal.ROUND_HALF_UP);
    BigDecimal bd3 = bd1.divide(bd2).setScale(2,BigDecimal.ROUND_HALF_UP);
    System.out.println("result: " + bd3);

但是,我一直收到同样的异常。有人可以告诉我我在哪里出错了吗?

However, I keep getting the same exception. Anyone able to show me where I have made a mistake?

推荐答案

使用 divide 您应该使用 MathContext ,以防精确结果具有无穷多个小数位数(您的情况):

When using divide you should use a MathContext in case the exact result has an infinite number of decimals (which is your case):

MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
BigDecimal bd3 = bd1.divide(bd2, mc);

或者:

BigDecimal bd3 = bd1.divide(bd2, RoundingMode.HALF_UP);

这篇关于是什么原因导致“不终止的十进制扩展”? BigDecimal.divide的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:53