Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Using the "==" Operator with Double or Float

Avoid causing and endless loop with float or double values in Java.


advertisement

WEBINAR:

On-Demand

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017


for (float f = 10f; f!=0; f-=0.1){
   System.out.println(f);
}

The code above causes an endless loop, it doesn't act as expected, because 0.1 is an infinite binary decimal and f will never be exactly 0. Normally, you should never compare float or double values with the equality operator "==", you should always use less than or greater than. Java compilers should be changed to issue a warning in that case. Or even make "==" an illegal operation for floating point types in the Java Language Spec.

for (float f=10f; f0; f-=0.1){
      System.out.println(f);
}

 

Visit the DevX Tip Bank

 





   
Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies--XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date