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
returns1: 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.
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 objectsBigDecimal 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 + ".");}}}
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.
Free Resources