DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to compare doubles in java.

The Compare() method of Double class is a built-in method in java that compares two specified double values. The sign returned of integer values is the same as that of an integer that will be returned during the function call.


title: "How to compare doubles in java."
tags: java

canonical_url: https://kodlogs.com/blog/1046/how-to-compare-doubles-in-java

Syntax:

public static int compare(double d1, double d2)

Parameters:

This accept work with two parameters;

  • d1: The first Double value that needs to compare.
  • d2: The second Double value that needs to compare. ##Return Value: This function will return the following values.

0: if both the numbers are equal.
Negative value: if the value of d1 is less than d2.
Positive value: if the value of d1 is larger than d2.

Example Code:

import java.lang.Double;

public class GFG {

               public static void main(String[] args)

               {
                     // Get the two double values

                               // to be compared

                               Double d1 = 10d;

                               Double d2 = 1023d;



                               // function call to compare two double values

                               // if d1 and d2 are same                             

                           if (Double.compare(d1, d2) == 0) {

                                               System.out.println("d1=d2");

                               }

//id d1 is less than d2

                               else if (Double.compare(d1, d2) < 0) {

                                               System.out.println("d1<d2");

                               }

//if d1 is greater than d2

                               else {

                                               System.out.println("d1>d2");

                               }

               }

} 
Enter fullscreen mode Exit fullscreen mode

Output:

The output of the above program will be d1.

Top comments (0)