# Rounding a float value

Vallabhaneni Suresh Kumar

Ranch Hand

Posts: 68

David Ulicny

Ranch Hand

Posts: 724

Peter Chase

Ranch Hand

Posts: 1970

posted 11 years ago

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.

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.