The java.math.BigDecimal.compareTo(BigDecimal bg) method checks for equality of this BigDecimal and BigDecimal object bg passed as parameter. The method considers two equal BigDecimal objects even if they are equal in value irrespective of the scale.
public int compareTo(BigDecimal bg)
Parameters:This function accepts only one BigDecimal object of BigDecimal type for comparison with this BigDecimal object.
Return Value:This method can return the following values :
- 0 : if value of this BigDecimal is equal to that of BigDecimal object passed as parameter.
- 1 : if value of this BigDecimal is greater than that of BigDecimal object passed as parameter.
- -1 : if value of this BigDecimal is less than that of BigDecimal object passed as parameter.
Note: The function returns true when it compares 124.0 and 124.0000, as it does not compare the scale of the two BigDecimal objects.
Input : b1 = new BigDecimal("4743.0008"), b2 = new BigDecimal("4743.00001") b1.compareTo(b2) Output : 1 Input : b1 = new BigDecimal(4743), b2 = new BigDecimal("4743.00"); b1.compareTo(b2) Output : 0
Below programs illustrate the working of compareTo() function of BigDecimal class:
Program 1: For greater than condition:
67891 is greater than 12346.
Program 2: For equal condition:
67891 and 67891.000 are equal.
Program 3: For less than condition:
4743.00001 is lesser than 4743.0008.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.