划分BigDecimals会导致ArithmeticException

dtr*_*unk 6 java math

可能重复:
在BigDecimal.divide期间抛出ArithmeticException

这导致ArithmeticException:http://ideone.com/RXeZw

提供比例和舍入模式将给我错误的结果.此示例应输出50.03%.如何正确地圆?

为便于参考,这是代码:

BigDecimal priceDiff = BigDecimal.ONE
     .subtract(new BigDecimal(9.99)
     .divide(new BigDecimal(19.99)))
     .multiply(new BigDecimal(100));
System.out.println(priceDiff.toPlainString());
Run Code Online (Sandbox Code Playgroud)

Kep*_*pil 9

BigDecimal.divide(BigDecimal divisor)如果无法准确表示结果,则抛出ArithmeticException.
您必须使用提供MathContext或RoundingMode来告诉您如何处理此问题.例如:

public class Test {
    public static void main(String[] args) throws java.lang.Exception {
        BigDecimal priceDiff = BigDecimal.ONE.subtract(new BigDecimal("9.99").divide(new BigDecimal("19.99"), MathContext.DECIMAL128))
                                             .multiply(new BigDecimal(100));
        System.out.println(priceDiff.toPlainString());
    }
}
Run Code Online (Sandbox Code Playgroud)

工作和打印

50.0250125062531265632816408204102100
Run Code Online (Sandbox Code Playgroud)

另外,请注意使用BigDecimal(String)构造函数以避免在BigDecimal使用double文字创建时出现问题.