This example shows how to perform basic mathematical operations using BigDecimals.

1.Addition

BigDecimal a = new BigDecimal("5");
BigDecimal b = new BigDecimal("7");

//Equivalent to result = a + b
BigDecimal result = a.add(b);
System.out.println(result);

Result : 12

2.Subtraction

BigDecimal a = new BigDecimal("5");
BigDecimal b = new BigDecimal("7");

//Equivalent to result = a - b
BigDecimal result = a.subtract(b);
System.out.println(result);

Result : -2

3.Multiplication

When multiplying two BigDecimals the result is going to have scale equal to the sum of the scales of operands.

BigDecimal a = new BigDecimal("5.11");
BigDecimal b = new BigDecimal("7.221");

//Equivalent to result = a * b
BigDecimal result = a.multiply(b);
System.out.println(result);

Result : 36.89931

To change the scale of the result use the overloaded multiply method which allows passing MathContext - an object describing the rules for operators, in particular the precision and rounding mode of the result. For more information about available rounding modes please refer to the Oracle Documentation.

BigDecimal a = new BigDecimal("5.11");
BigDecimal b = new BigDecimal("7.221");

MathContext returnRules = new MathContext(4, RoundingMode.HALF_DOWN);

//Equivalent to result = a * b
BigDecimal result = a.multiply(b, returnRules);
System.out.println(result);

Result : 36.90

4.Division

Division is a bit more complicated than the other arithmetic operations, for instance consider the below example:

BigDecimal a = new BigDecimal("5");
BigDecimal b = new BigDecimal("7");

BigDecimal result = a.divide(b);
System.out.println(result);

We would expect this to give something similar to : 0.7142857142857143, but we would get:

Result: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

This would work perfectly well when the result would be a terminating decimal say if I wanted to divide 5 by 2, but for those numbers which upon dividing would give a non terminating result we would get an ArithmeticException. In the real world scenario, one cannot predict the values that would be encountered during the division, so we need to specify the Scale and the Rounding Mode for BigDecimal division. For more information on the Scale and Rounding Mode, refer the Oracle Documentation.