BigDecimal compareTo() Function in Java

Last Updated : 9 Jan, 2026

The BigDecimal.compareTo() method compares two BigDecimal objects based on their numerical value only, ignoring scale differences, and returns an integer indicating whether the current value is less than, equal to, or greater than the specified BigDecimal.

Example:

Java
import java.math.BigDecimal;
class GFG {
    public static void main(String[] args) {
        BigDecimal b1 = new BigDecimal("10.5");
        BigDecimal b2 = new BigDecimal("8.2");
        System.out.println(b1.compareTo(b2));
    }
}

Output
1

Explanation: Since 10.5 is greater than 8.2, the compareTo() method returns 1.

Syntax

public int compareTo(BigDecimal bg);

Parameters: 'bg' the BigDecimal object to be compared with the current object.

Return Value:

  • 0: both values are numerically equal.
  • 1: current BigDecimal is greater than bg.
  • -1: current BigDecimal is less than bg.

Example 1: Greater Than

This example shows that compareTo() compares numeric values only and ignores scale when determining which value is greater.

Java
import java.io.*;
import java.math.*;
class GFG {
    public static void main (String[] args) {
        BigDecimal b1 = new BigDecimal("4743.0008");
        BigDecimal b2 = new BigDecimal("4743.00001");
        System.out.println(b1.compareTo(b2));

    }
}

Output
1

Explanation:

  • b1.compareTo(b2) compares the numeric values.
  • Since 4743.0008 > 4743.00001, the method returns 1.

Example 2: Equal Values (Different Scale)

BigDecimal.compareTo() considers values equal regardless of scale differences.

Java
import java.io.*;
import java.math.*;

public class GFG {
    public static void main(String[] args)
    {
       BigDecimal b1 = new BigDecimal(4743);
       BigDecimal b2 = new BigDecimal("4743.00");
       System.out.println(b1.compareTo(b2));
    }
}

Output
0

Explanation:

  • compareTo() ignores scale and compares only the value.
  • Since both values are numerically equal, the method returns 0, which is printed to the console.

Example 3: Less Than

This example shows how BigDecimal.compareTo() determines that one value is smaller than another based on numeric value, ignoring scale.

Java
import java.io.*;
import java.math.*;

public class GFG {

    public static void main(String[] args)
    {

        BigDecimal b1 = new BigDecimal("4743.00001");
        BigDecimal b2 = new BigDecimal("4743.0008");
        System.out.println(b1.compareTo(b2));

    }
}

Output
-1

Explanation:

  • b1.compareTo(b2) compares the numeric values of both BigDecimal objects.
  • Since 4743.00001 is less than 4743.0008, the method returns -1, indicating b1 < b2.

Note : compareTo() compares only the value, not the scale.This behavior is different from equals(), which considers both value and scale.

Comment