Math.round() vs toFixed()

9 01 2009

Something I recently came across when working with calculations which were to 4 decimal places and then had to be rounded to 2 decimal places, was rounding in Javascript.

The code that was originally doing this was toFixed(x) where x is the number of decimal places required. After some incorrect calcualtions and investigation, I found that toFixed(x) instead of rounding to 2 decimal places, was discarding anything after the 2 decimal places. More chopping rather than rounding!

Then I looked into the Math.round function to see if this would be a better alternative and it was. Using the following logic, the totals now round nicely to 2 decimal places (this can be adapted for however many decimal places are required).

Math.round(total * 10^x) / 10^x (where x is the number of decimal places required)

Therefore my code reads…

Math.round(total * 100) / 100

And this gives me 2 lovely decimal places, rounded, not chopped.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: