CKTIS / Java
BigDecimal.subtract — subtract decimal values
Subtract two `BigDecimal` values exactly, or round the difference using a `MathContext`. Neither operand changes.
Version: Java SE 21
Syntax
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal subtract(BigDecimal subtrahend, MathContext mc)BigDecimal.subtract is an instance method of java.math.BigDecimal. The call a.subtract(b) computes a − b: it subtracts the argument from the object you call the method on. Order matters. The - operator does not work on BigDecimal objects.
subtract(BigDecimal) returns the exact difference without rounding. Its scale is Math.max(a.scale(), b.scale()). A nonnegative scale counts digits after the decimal point, including trailing zeros. BigDecimal is immutable, so neither operand changes. Store the return value if you need the difference later.
subtract(BigDecimal, MathContext) rounds the exact difference if needed, using the context's precision and rounding mode. Precision counts significant digits, not decimal places. Precision 0, as in MathContext.UNLIMITED, means exact arithmetic with no rounding. If rounding is required but the mode is RoundingMode.UNNECESSARY, the method throws ArithmeticException. Passing null as the amount to subtract or as the context throws 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.30");
BigDecimal b = new BigDecimal("0.456");
BigDecimal exact = a.subtract(b);
BigDecimal rounded = a.subtract(b, new MathContext(3, RoundingMode.HALF_UP));
System.out.println(exact.toPlainString());
System.out.println(exact.scale());
System.out.println(rounded.toPlainString());
System.out.println(a.toPlainString());
System.out.println(b.toPlainString());
}
}Result
11.844 3 11.8 12.30 0.456
The string constructors preserve the exact decimal inputs without converting through `double`. The program prints the exact difference `11.844`, its scale `3`, the result `11.8` rounded to three significant digits with `HALF_UP`, and finally the unchanged operands `12.30` and `0.456`.
Related lessons
- Java · Lesson 69 · Basic · Version: 2