Re: Adding int to a float
Frank Cisco wrote:
How do you get an accurate addition of a float and an int?
int i = 5454697;
float f = 0.7388774F;
float result = new Integer(i).floatValue()+f;
result=5454697.5 ??
Surely it should be 5454697.7388774? If I use double it's fine, but I
need to use float
5454697.7388774 is not exactly representable in either double or float,
but double can get much closer. The double approximation happens to be
close enough to 5454697.7388774 that its toString() is "5454697.7388774".
Incidentally, "new Integer(i).floatValue()" is unnecessary. i+f would
convert i to float and do the addition.
Float only has 24 significant bits, the equivalent of slightly over 7
significant decimal digits, so you should expect rounding error to
appear around the seventh or eighth decimal digit when adding numbers of
similar magnitude.
If you need exact arithmetic on decimal fractions, you should use
neither double nor float, but BigDecimal. If some rounding error is
acceptable, but you need to get reasonable precision without doing a lot
of numerical analysis, use double.
I strongly recommend against float unless you have a really good
understanding of numerical analysis, and the benefits of float in your
application justify significant extra work, because being sure of
getting usable results from its limited precision is difficult. A
non-trivial calculation with float can have results that are all,
or mainly, rounding error.
Even if your inputs and outputs are in float, you will get better
precision by converting to double for the calculations and converting
back again at the end.
Patricia