BigDecimal compareTo

In this post,we will see about Bigdecimal‘s compareTo method.This method is used to compare two BigDecimals.

Syntax

Return type

CompareTo method returns -1,0,1
-1 : First BigDeicmal is less than second BigDecimal
0 : First BigDecimal is equal to second BigDecimal
1 : First BigDecimal is greater than second BigDecimal

BigDecimal CompareTo example

Let’s see compareTo method with the help of example.

Above program will generate below output.

First BigDecimal is greater than Second BigDecimal

BigDecimal compareTo vs equals

Unlike equals method, if two BigDecimals have same value but different scale, compareTo method will return 0.It means compareTo method will consider them equal.

When you run above program, you will get below output.

Using BigDecimal compareTo method
First BigDecimal is equal to Second BigDecimal
=================
Using BigDecimal equals method
First BigDecimal is not equal to Second BigDecimal

Comparing BigDecimal with Zero

There are multiple ways to compare a BigDecimal with 0.Best way is:

Let’s see with the help of simple example.

When you run above program, you will get below output.

BigDecimal is greater than Zero

That’s all about BigDecimal CompareTo method.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *