Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Rounding a float value

 
Vallabhaneni Suresh Kumar
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • 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?
 
David Ulicny
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you post the code? I think there must be a bug.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic