Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Expertise: Beginner
Jun 21, 2000



Application Security Testing: An Integral Part of DevOps

Incorrect Rounding with Math.pow


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?


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:


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.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date