Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

BigDecimal: exact decimal arithmetic, scale, and comparison

Read decimal text without converting through `double`, calculate exactly, choose a scale and rounding rule, and compare numbers independently of their scale.

Version: Java SE 21

Syntax

java.math.BigDecimal — Java SE 21

BigDecimal(String val)
BigDecimal add(BigDecimal augend)
BigDecimal multiply(BigDecimal multiplicand)
BigDecimal setScale(int newScale)
BigDecimal setScale(int newScale, RoundingMode roundingMode)
BigDecimal stripTrailingZeros()
int compareTo(BigDecimal val)
String toPlainString()

RoundingMode: java.math.RoundingMode

In Java SE 21, the BigDecimal(String) constructor in java.math reads a decimal value exactly without going through double. Use a decimal point, not a comma; whitespace and digit grouping separators are not accepted. Invalid text throws NumberFormatException. Without an exponent, scale counts the digits after the point, including trailing zeros; an explicit exponent is subtracted from that scale.

The one-argument BigDecimal.add and BigDecimal.multiply methods return the exact sum and product. The sum uses the larger operand scale; the product's preferred scale is the sum of the operand scales. In JDK 21, if the sum of the scales is outside the int range, multiplication can throw ArithmeticException. If the receiver (this) is zero, it instead returns zero with the scale clamped to the nearest int bound. Overloads that take a MathContext can round according to that context. BigDecimal is immutable: keep the returned result, because the operands do not change.

BigDecimal.setScale chooses the result's scale. setScale(int) throws ArithmeticException if rounding would be needed; setScale(int, RoundingMode) lets you choose a rule. HALF_UP rounds to the nearest value, with ties away from zero; UNNECESSARY throws ArithmeticException if rounding is needed. The setScale(int, int) overload is deprecated.

BigDecimal.stripTrailingZeros removes trailing zeros from the representation without changing the value. Scale can become negative, as it does for 600.0 after stripping (scale -2); for zero it returns BigDecimal.ZERO. Scale overflow throws ArithmeticException. BigDecimal.toPlainString returns text with no exponent or locale-specific formatting. To get a fixed number of decimal places, set the scale first. Parsing the text again preserves the value but may not preserve the scale.

BigDecimal.compareTo compares numbers regardless of scale: it returns -1, 0, or 1 when the first operand is less than, equal to, or greater than the second. Use a.compareTo(b) == 0 for numeric equality; equals requires both the same value and the same scale, so it returns false for 2.0 and 2.00.

Examples

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

public class Main {
    public static void main(String[] args) {
        BigDecimal unitPrice = new BigDecimal("2.500");
        BigDecimal quantity = new BigDecimal("3");
        BigDecimal fee = new BigDecimal("0.005");
        BigDecimal exact = unitPrice.multiply(quantity).add(fee);
        BigDecimal rounded = exact.setScale(2, RoundingMode.HALF_UP);

        BigDecimal stripped = new BigDecimal("600.0").stripTrailingZeros();
        BigDecimal sameValue = new BigDecimal("600.00");

        System.out.println("exact: " + exact.toPlainString());
        System.out.println("rounded: " + rounded.toPlainString());
        System.out.println("stripped scale: " + stripped.scale());
        System.out.println("plain: " + stripped.toPlainString());
        System.out.println("compareTo: " + stripped.compareTo(sameValue));
        System.out.println("equals: " + stripped.equals(sameValue));
    }
}

Result

exact: 7.505
rounded: 7.51
stripped scale: -2
plain: 600
compareTo: 0
equals: false

The exact result `7.505` rounds to `7.51`. Stripping zeros from `600.0` gives scale `-2`, but the exponent-free text is `600`. Comparing it with `600.00` gives `0`, while `equals` returns `false`.

Related lessons

  • Java · Lesson 60 · Intermediate · Version: 2

Sources