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.