Right way to compare double and float in Java?

Soma - Dec 2 '22 - - Dev Community

If you have been doing Java programming then you may know that the use of == operator is not the correct way to compare floating point values in Java. If you use equality operator to compare float and double variables then it can cause an endless loop in Java, but is there a way to prevent that loop from running infinitely? Yes, instead of using == operator, you can use relational operator e.g. less than (<) or greater than (>) to compare float and double values.

By changing the above code as following, you can prevent the loop from infinitely  :

for(double balance = 10; balance > 0; balance-=0.1) {\
   System.out.println(balance);\
}
Enter fullscreen mode Exit fullscreen mode

If you think little bit than you will realize that greater than will definitely end this loop, but don't expect it to print numbers like 9.9, 9.8, 9.7 because floating point numbers are just approximation, they are not exact. Some numbers e.g. 1/3 cannot be represented exactly using float and double in Java.

After running following program in your computer you may end up with something like this

Java Program  to compare float and double values:

Here is the complete Java program to check if two float or double values are equal, greater or less than of each other.

public class FloatComparator {

    public static void main(String args[]){
        float firstValue = 10.2f;
        float secondValue = 10.3f;
        float thirdValue = 10.2f;

        if(firstValue > secondValue){
            System.out.print("First Value and second value are not equal");
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

 
By the way, this is not the only way, you can also use equals() method of Wrapper classes like Float and Double to do the floating point comparison. They are in fact preferred way if you want to check if two floating point values are equal or not but if you just want to know that they are not equal then using < and > operator is rather easy.

That's all about right way to compare float and double values in loop in Java. This simple trick of using logical operator less than and greater than instead of equality operator to compare float and double variable can save you a lot of headache.

. . . . . . . . . . . . . . . . . . . . . . . . .