4

I am creating a script for calculating an order total. There are certain variables that can change the price and therefore some long-digit decimals will occur.

Is toFixed() precise enough to round these numbers and always get the same result?

Edit: The solution I came up with is to use this:

Number.prototype.toCurrency = function(){
    return Math.round(this*100)/100;
}

Is this sufficient for consistency?

twiz
  • 9,041
  • 8
  • 52
  • 84
  • No! Look at this: http://stackoverflow.com/q/566564/1001563 – noob Sep 01 '12 at 21:04
  • The `toFixed()` routine just gives you a string representation. If you do currency math with JavaScript numerics you'll have problems. The basic problem is that 2 and 5 are relatively prime. – Pointy Sep 01 '12 at 21:04

1 Answers1

2

You shouldn't use toFixed for this as it doesn't work consistently across browsers.

All numbers in Javascript are double precision floating point numbers. Floating point numbers are by definition not exact, therefore the number representation itself isn't precise enough to always get an exact result.

If you want a predictable result in Javascript, you have to keep the precision limitations of the numbers in mind, so that you always have a big enough margin to be able to round the number correctly.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • please provide sources / references to your first claim (*it doesn't work consistently across browsers*). – Eliran Malka Sep 01 '12 at 21:15
  • I don't entirely understand what you mean by _you have to keep the precision limitations of the numbers in mind, so that you always have a big enough margin to be able to round the number correctly._ With currency using only 2 decimal digits, shouldn't this be enough margin? – twiz Sep 01 '12 at 21:31
  • @twiz: Yes, that would give you plenty of margin for almost any calculation. – Guffa Sep 01 '12 at 22:12