McKirahan <News (AT) McKirahan (DOT) com> wrote
Quote:
How do I add floating point numbers accurately?
The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.39999999999998 instead of 191.40. |
If you happen to be handling money, it's preferable to avoid floating point calculations by working in pennies, then
formatting the result.
var pennies=12305
var dollars=Math.floor( pennies / 100 ), cents = pennies % 100;
result = dollars + '.' + ((cents < 10) ? ('0' + cents) : cents);
--
S.C.