• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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
1
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic