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

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
Updated on: 2026-03-11T22:50:42+05:30

831 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements