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?
The one argument
BigDecimal.Divide
throws anArithmeticException
if the quotient is a non-terminating decimal (361/6 is 60.1666666...):To avoid this use the
overload
with a secondRoundingMode
parameter.I.e., you tell BigDecimal exactly what you expect from the division result.