304 North Cardinal St.
Dorchester Center, MA 02124

# How to compare two BigDecimals in Java

## How to compare two BigDecimals in Java Answer

`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.
##### How to compare two BigDecimals in Java Review:

In our experience, we suggest you solve this How to compare two BigDecimals in Java and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the How to compare two BigDecimals in Java

Find on Educative

##### Conclusion:

I hope this How to compare two BigDecimals in Java would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions