Related Tags

compare
bigdecimals
java

# How to compare two BigDecimals in Java

A BigDecimal consists of a 32-bit integer scale; it is used to handle very large and very small floating-point numbers.

Java provides the built-in function compareTo() which compares the two BigDecimals. The comparison can not be done using the >, < or = operators as these operators can only be used for the primitive data types like int, long and double.

## CompareTo returns

• 1: when the first BigDecimal is greater than the second BigDecimal.

• 0: when the first BigDecimal is equal to the second BigDecimal.

• -1: when the first BigDecimal is less than the second BigDecimal.

Note: The first BigDecimal is the number which calls the function, ​and the second BigDecimal is the number which is passed as an argument in the function.

## Code

The following code explains how to compare two BigDecimals:

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

class example {

public static void main(String[] args)
{

// Creating 2 BigDecimal objects
BigDecimal First, Second;

First = new BigDecimal("47653.002");
Second= new BigDecimal("22121.302");

if (First.compareTo(Second) == 0) {
System.out.println(First + " and " + Second + " are equal.");
}
else if (First.compareTo(Second) == 1) {
System.out.println(First + " is greater than " + Second + ".");
}
else {
System.out.println(First + " is lesser than " + Second + ".");
}
}
} 

### Things to try

• Try changing the numbers in the code to check the inequality or equality.

• The numbers are placed between ("") so that they do not become too long. Try removing the double quotes and check the effect.

RELATED TAGS

compare
bigdecimals
java