It's not a secret anymore!
The moose likes Beginning Java and the fly likes Rounding a float value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Rounding a float value" Watch "Rounding a float value" New topic

Rounding a float value

Vallabhaneni Suresh Kumar
Ranch Hand

Joined: Mar 01, 2004
Posts: 68
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

Joined: Aug 04, 2004
Posts: 724
Could you post the code? I think there must be a bug.

SCJP<br />SCWCD <br />ICSD(286)<br />MCP 70-216
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: Rounding a float value
It's not a secret anymore!