Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the division of two BigDecimal numbers in Java throws the ArithmeticException?

Tags:

java

Let's look at the following code snippet in Java.

package division;

import java.math.BigDecimal;

final public class Main
{
    public static void main(String[] args)
    {
        BigDecimal a = new BigDecimal(2);
        BigDecimal b = new BigDecimal(3);

        System.out.println(a.multiply(b));
        System.out.println(a.add(b));
        System.out.println(b.subtract(a));
        System.out.println(a.divide(b));
    }
}

In the above code snippet, all of the operations except the last one (division) are performed successfully. An attempt to divide two BigDecimal numbers in Java throws the java.lang.ArithmeticException. Why? What is the solution to this problem?

like image 925
Lion Avatar asked Apr 05 '12 17:04

Lion


1 Answers

From the BigDecimal#divide(BigDecimal) documentation:

...if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

In your specific case "2/3" has a non-terminating decimal expansion (0.6666...) so you'll have to use a form of divide() which takes a scale and/or RoundingMode to resolve the infinite representation. For example:

BigDecimal a = new BigDecimal(2);
BigDecimal b = new BigDecimal(3);
a.divide(b, 4, RoundingMode.CEILING); // => 0.6667
a.divide(b, 4, RoundingMode.FLOOR);   // => 0.6666
like image 139
maerics Avatar answered Jan 02 '23 04:01

maerics