Java Double compare example

Java 8Object Oriented ProgrammingProgramming

To compare Double in Java, use the following methods −

Method 1 − compareTo() method in Java

The java.lang.Double.compareTo() method compares two Double objects.

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String args[]) {
      Double d1 = new Double("395.24");
      Double d2 = new Double("323.30");
      int res = d1.compareTo(d2);
      if(res > 0) {
         System.out.println("d1 is greater than d2");
      }
      else if(res < 0) {
         System.out.println("d1 is less than d2");
      }
      else {
         System.out.println("d1 is equal to d2");
      }
   }
}

Output

d1 is greater than d2

Method 2 − compare() method in Java

The java.lang.Double.compare() method compares two double values objects numerically.

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String args[]) {
      Double d1 = new Double("195.24");
      Double d2 = new Double("323.30");
      int res = Double.compare(d1, d2);
      if(res > 0) {
         System.out.println("d1 is greater than d2");
      }
      else if(res < 0) {
         System.out.println("d1 is less than d2");
      }
      else {
         System.out.println("d1 is equal to d2");
      }
   }
}

Output

d1 is less than d2
raja
Published on 11-Dec-2018 06:19:44
Advertisements