JavaScript Rounding Errors

March 2009

Floating-point rounding errors are so bleedin' simple and obvious that I am hugely embarrassed that I was bitten by a host of them at work this week. This is something usually tackled in "Programming for beginners" hence me cringing under my desk.

It's complicated but in short the problem happens when computers perform calculations on certain numbers, the result can be fractionally wrong. See Wikipedia for more detail. Here is an example:

We would expect the calculation 100 * 10 to give the answer 1000. This works fine:

We would expect the calculation 132.32 * 10 to give the answer 1323.2, but instead this has fail:

So once and for all, and much to my embarrassment, here are a couple of functions I'll publish here so I have no excuse to make this mistake ever, ever again. Round() will give you back a number, accurate to the number of decimal places you specify, and RoundFixed() returns a string fixed to the required number of decimal places, e.g. useful when dealing with currency, £1.2 is accurate but better represented as £1.20.

function Round(Number, DecimalPlaces) {
   return Math.round(parseFloat(Number) * Math.pow(10, DecimalPlaces)) / Math.pow(10, DecimalPlaces);
}

function RoundFixed(Number, DecimalPlaces) {
   return Round(Number, DecimalPlaces).toFixed(DecimalPlaces);
}

Let's try that troublesome number again: Round(132.32 * 10, 2)
And again: RoundFixed(132.32 * 10, 2)
If you find these useful, that's great, but don't tell 'em Jon sent you.

Jon Combe