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?
From the
BigDecimal#divide(BigDecimal)documentation: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/orRoundingModeto resolve the infinite representation. For example: