Reputation: 10558
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?
Upvotes: 4
Views: 1836
Reputation: 700342
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.
Upvotes: 2