Comparison of double and float primitive types in Java


If we compare a float and a double value with .5 or .0 or .1235 (ending with 5 or 0), then == operator returns true, otherwise it will return false. See the below example.

Example

Live Demo

public class Tester {
   public static void main(String[] args) {
      double d1 = 2.5;
      float f1 = 2.5f;
      System.out.println(d1 == f1);

      double d2 = 2.4;
      float f2 = 2.4f;
      System.out.println(d2 == f2);
   }
}

Output

true
false

The reason behind this logic is the approximation of float and decimal. Float data type is a single-precision 32-bit IEEE 754 floating point and double data type is a double-precision 64-bit IEEE 754 floating point. A number ending with 5 or 0 can be represented exactly in both double and float.

In case of other numbers, it is similar to comparing 0.3333 to 0.33333333 where precision of later is high.

Correct way of comparing double and float

In order to compare double and float, check the difference of two to be greater than or less than a particular margin. See the example below.

Example

Live Demo

public class Tester {
   public static void main(String[] args) {
      double d1 = 2.5;
      float f1 = 2.5f;

      System.out.println(d1 == f1);

      double d2 = 2.4;
      float f2 = 2.4f;
      double margin = 0.0000001;

      System.out.println(compareNumbers(d2, f2, margin));
   }  

   private static boolean compareNumbers(double d, float f, double margin) {
      if(Math.abs(d - f) < margin) {
         return true;
      }        
      return false;
   }
}

Output

true
true

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Jun-2020

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements