- Java.math package classes
- Java.math - Home
- Java.math - BigDecimal
- Java.math - BigInteger
- Java.math - MathContext
- Java.math package extras
- Java.math - Enumerations
- Java.math - Discussion
Java.math.BigDecimal.compareTo() Method
Description
The java.math.BigDecimal.compareTo(BigDecimal val) compares the BigDecimal Object with the specified BigDecimal value.
Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method.
This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=).
The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.
Specified by
compareTo in interface Comparable<BigDecimal>
Declaration
Following is the declaration for java.math.BigDecimal.compareTo() method.
public int compareTo(BigDecimal val)
Parameters
val − Value to which this BigDecimal is to be compared.
Return Value
This method returns -1 if the BigDecimal is less than val, 1 if the BigDecimal is greater than val and 0 if the BigDecimal is equal to val
Exception
NA
Example
The following example shows the usage of math.BigDecimal.compareTo() method.
package com.tutorialspoint; import java.math.*; public class BigDecimalDemo { public static void main(String[] args) { // create 2 BigDecimal objects BigDecimal bg1, bg2; bg1 = new BigDecimal("10"); bg2 = new BigDecimal("20"); //create int object int res; res = bg1.compareTo(bg2); // compare bg1 with bg2 String str1 = "Both values are equal "; String str2 = "First Value is greater "; String str3 = "Second value is greater"; if( res == 0 ) System.out.println( str1 ); else if( res == 1 ) System.out.println( str2 ); else if( res == -1 ) System.out.println( str3 ); } }
Let us compile and run the above program, this will produce the following result −
Second value is greater