Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Rounding a float value

 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I had a variable of type float like float number=1.1f. When I am adding some other float value say 0.1f to it, it is giving 0.2000001 instead of 1.2. How to get the desired value?
 
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you post the code? I think there must be a bug.
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you really added 0.1f to 1.1f and got 0.2000001f, then your program or (highly unlikely) the Java runtime has a bug. I'm presuming that you mean that you got 1.2000001f.

In that case, you are just seeing that floating-point arithmetic is not exact. You can't rely on the accuracy of the last digit. In some complex calculations, the inaccuracy extends to more digits. That's just a fact of life of computing and nothing to do with Java.

If it is just the displayed value that you care about, you should format your floating-point value using NumberFormat or similar.

Often, when people use floating-point arithmetic, they could and should actually use integer arithmetic instead. Arithmetic operations do not suffer rounding errors (in most circumstances) and are generally faster (though modern FPUs may make that less true). The classic example is currency. People sometimes do calculations in floating-point numbers of dollars, for instance. Instead, they should do their calculations in integer numbers of cents.
 
What's that smell? I think this tiny ad may have stepped in something.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic