Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

BigDecimal.compareTo — Compare decimal values

`BigDecimal.compareTo` compares numeric values without treating different scales as different values. Test its result against zero for ordering or numeric equality.

Version: Java SE 21

Syntax

public int compareTo(BigDecimal val)

// If x and y are BigDecimal values:
x.compareTo(y) < 0   // x is numerically less than y
x.compareTo(y) == 0  // x and y are numerically equal
x.compareTo(y) > 0   // x is numerically greater than y

In Java SE 21, BigDecimal.compareTo is an instance method in java.math.BigDecimal that implements Comparable<BigDecimal>. Its signature is compareTo(BigDecimal val), with one BigDecimal argument; there is no overload that takes a double or String directly. Passing null throws NullPointerException.

x.compareTo(y) returns an int: -1 if x is numerically smaller than y, 0 if the values are equal, or 1 if x is greater. Compare the result against zero, as in x.compareTo(y) < 0 or x.compareTo(y) == 0. It is not the difference between the numbers. The general Comparable contract specifies only the sign; BigDecimal guarantees these three exact return values.

The comparison does not round either value or change either object. 2.0 and 2.00 have the same numeric value, so compareTo returns 0. Their scales are different (1 and 2), so equals(Object) returns false: it requires both value and scale to match.

Applying == directly to two BigDecimal references yields true if they refer to the same object or if both are null. It does not compare numeric values. Because natural ordering differs from equals, a TreeSet<BigDecimal> without a custom comparator treats 2.0 and 2.00 as one element.

Examples

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BigDecimal a = new BigDecimal("2.0");
        BigDecimal b = new BigDecimal("2.00");
        BigDecimal c = new BigDecimal("3.0");

        System.out.println(a.compareTo(b));
        System.out.println(a.equals(b));
        System.out.println(a.compareTo(c));
        System.out.println(c.compareTo(a));
    }
}

Result

0
false
-1
1

The string constructor arguments preserve scales `1` and `2` for `a` and `b`. The first two lines contrast numeric comparison with `equals`; the last two show how reversing the operands changes the sign.

Related lessons

  • Java · Lesson 69 · Basic · Version: 2

Sources