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:
...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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With