dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
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
Language:
Expertise: Beginner
Jun 21, 2000

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Incorrect Rounding with Math.pow

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.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

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