Java BigDecimal divideAndRemainder throws Division impossible exception

时间:2019-03-17 22:28:57

标签: java bigdecimal

Check out this code. It works for number like 704 but from 705 starts getting a Division Impossible error:

import java.math.*;

public class Test {
  public static void main(String[] argv) throws Exception {
    BigDecimal totalDuration = new BigDecimal(705);

    int scale = 2;
    MathContext mc = new MathContext(scale, RoundingMode.HALF_UP);
    System.out.println(totalDuration.divideAndRemainder(new BigDecimal(5), mc));
  }
}

I'm using JDK 11.

Error thrown:

Exception in thread "main" java.lang.ArithmeticException: Division impossible
    at java.base/java.math.BigDecimal.divideToIntegralValue(BigDecimal.java:1880)
    at java.base/java.math.BigDecimal.divideAndRemainder(BigDecimal.java:2012)
    at Test.main(Test.java:9)

2 个答案:

答案 0 :(得分:3)

Have you checked documentation for BigDecimal.divideAndRemainder?

It says:

throws ArithmeticException if the result is inexact but the rounding mode is UNNECESSARY, or mc.precision > 0 and the result of this.divideToIntgralValue(divisor) would require a precision of more than mc.precision digits.

So int scale = 2; is just not enough for this operation, if you change it to int scale = 3;, it works nice.

答案 1 :(得分:1)

705 / 5 == 141, and 141 can't be represented as as 2 digits.

The docs say:

ArithmeticException is thrown if the integer part of the exact quotient needs more than precision digits.

(Mildy paraphrased)

You need to have more precision. It works when scale is 3.

704 works presumably because the integer portion can be represented as two digits: 1.4E+2.