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

1.6k views Asked by At

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?

3

There are 3 answers

0
Nivas On BEST ANSWER

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.

0
Alex Botev On

This is as expected by the Java spec. You have not provided any scale, and since 361/6 = 60.1(6) it should throw that exception. If you want some rounding you should provide a scale, meaning how much digits after the decimal point to return, or you might want devideAndReminder for dividing with reminder.

0
Reimeus On

You could, say round to 5 decimal places:

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