Search code examples
javabigdecimalarithmeticexception

Certain BigDecimal numbers in Java when divided causes the ArithmeticException to be thrown


The following approach to divide two BegDecimal numbers works fine.

BigDecimal a=new BigDecimal(5);
BigDecimal b=new BigDecimal(2);
System.out.println(a.divide(b));

Output : 2.5


The following same approach however fails with the java.lang.ArithmeticException

BigDecimal c=new BigDecimal(361);
BigDecimal d=new BigDecimal(6);
System.out.println(c.divide(d));

The following is the complete exception stack trace.

Exception in thread "main" java.lang.ArithmeticException:
Non-terminating decimal expansion; no exact representable decimal result.
    at java.math.BigDecimal.divide(BigDecimal.java:1603)
    at currenttime.Main.main(Main.java:15)
Java Result: 1

What's the solution?


Solution

  • The one argument BigDecimal.Divide throws an ArithmeticException if the quotient is a non-terminating decimal (361/6 is 60.1666666...):

    Throws:
    ArithmeticException - if the exact quotient does not have a terminating decimal expansion

    To avoid this use the overload with a second RoundingMode parameter.

    I.e., you tell BigDecimal exactly what you expect from the division result.