Java67: Why you shouldn't use == with float and double in Java?
Thursday, September 3, 2015 Why you shouldn't use == with float and double in Java? In this article, you are going to learn why you shouldn't use == with float and double in Java? Especially for checking loop termination condition. Java programmers often make mistake of using floating point number in loop and checking condition with == operator, in worst case this could create an infinite loop, causing your Java application to hung. For example, following code will not work as you expect : for(double balance = 10; balance!=0; balance-=0.1) { System.out.println(balance); } You would think that, this code will print balance until balance reduced to zero. Since we are doing balance = balance - 0.1, you would expect it to print something like 10, 9.9, 9.8 and so on until it reaches zero. But for your surprise, this will cause an infinite loop in Java, it will never end, Why? because 0.1 is an infinite binary decimal, balance will never be exactly 0. This is the reason many programmers,Read full article from Java67: Why you shouldn't use == with float and double in Java?
No comments:
Post a Comment