Question:
I have noticed that all rounding to x decimals scripts uses the following format:
tenToPower = Math.pow(10, nDecimals);newNumber = String((Math.round(nNumber * tenToPower) / tenToPower));
However, that doesn’t work with numbers like 0.5005, yet DOES work with 0.50051. Any idea why, and how to fix the script above?
Answer:
Simply put, JavaScript is good at a lot of things, but math isn’t one of them.
If you take .5005 and multiply it by 1000, you and I get 500.5. That number, rounded, is 501. When JavaScript does that same multiplication, though, it gets a product of 500.49999999. That number, rounded, is 500.
You can try this out by entering the following into the location/address bar of your browser:
javascript:alert(.5005*1000)
Unfortunately, there’s no simple workaround for this problem. You might try multiplying by another power of ten and then dividing by that on the other side.