Saturday, 15 January 2022

How to compare float and double values in Java? Example Tutorial

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);
}


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:

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");
        }
       
    }
}



 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. 



No comments:

Post a Comment