Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

BigDecimal.add — exact and rounded addition

Add BigDecimal values exactly, or use MathContext to set the precision and rounding mode of the result.

Version: Java SE 21

Syntax

import java.math.BigDecimal;
import java.math.MathContext;

BigDecimal exact = a.add(b);
BigDecimal rounded = a.add(b, mc);

// Instance method signatures in java.math.BigDecimal:
// public BigDecimal add(BigDecimal augend)
// public BigDecimal add(BigDecimal augend, MathContext mc)

BigDecimal.add is an instance method of java.math.BigDecimal. In a.add(b), the receiver a and argument b are the two operands. You cannot add two BigDecimal objects with +. These objects are immutable: the method returns the result without changing either operand. Store or use the return value; a.add(b); by itself does not update a.

a.add(b) returns the exact sum with scale max(a.scale(), b.scale()). A nonnegative scale counts decimal places, including trailing zeros. A scale can also be negative: with scale -2, the value is the stored integer multiplied by 100.

a.add(b, mc) takes a MathContext from java.math. A positive precision limits the number of significant digits in the result, not the number of decimal places. The method rounds the exact sum if needed using the context's rounding mode, so the result's scale can change. With positive precision, if exactly one operand is zero, the result has the numerical value of the nonzero operand, rounded if needed. The result can have a different scale from the nonzero operand even when no rounding is needed. For example, adding 0.00 to 1 at precision 3 yields 1.00. Precision 0, as in MathContext.UNLIMITED, means addition without rounding.

If rounding would change the value, RoundingMode.UNNECESSARY causes an ArithmeticException. Passing null as b or mc causes a NullPointerException.

Examples

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        BigDecimal a = new BigDecimal("12.40");
        BigDecimal b = new BigDecimal("0.350");
        MathContext mc = new MathContext(3, RoundingMode.HALF_UP);

        BigDecimal exact = a.add(b);
        BigDecimal rounded = a.add(b, mc);

        System.out.println(exact.toPlainString());
        System.out.println(rounded.toPlainString());
        System.out.println(a.toPlainString());
    }
}

Result

12.750
12.8
12.40

The operands are constructed from strings to avoid a prior conversion to `double`. The exact sum `12.750` has scale 3; at three significant digits, `HALF_UP` gives `12.8`. The last line shows that `a` is still `12.40`.

Related lessons

  • Java · Lesson 4 · Basic · Version: 2
  • Java · Lesson 69 · Basic · Version: 2

Sources