Tuesday, 31 January 2012

Formatting numbers for decimals and significant digits in JavaScript


       Formatting numbers so they confirm to a specific format can be deceivingly tricky. For example, one of the most common tasks is to format a number for currency display- an integer followed by two decimals. You may be tempted to use number rounding to first shift the number's decimal places (via multiplication), round it, then shift the decimal back (via division) to pound the number into your hard earned dollar, though that won't work in many cases. For example, consider the number 120. Number rounding certainly won't get you to 120.00.
To easily format numbers for a specific number of trailing decimals or total digits (aka padding), JavaScript 1.5 introduces the below two nifty methods:
Methods Description
Number.toFixed(x) Formats any number for "x" number of trailing decimals. The number is rounded up, and "0"s are used after the decimal point if needed to create the desired decimal length.
Number.toPrecision(x) Formats any number so it is of "x" length. Also called significant digits. A decimal point and "0"s are used if needed to create the desired length.

Number.toFixed()

The best way to see all the subtleties of toFixed() is to see it in action:
var profits=2489.8237
profits.toFixed(3) //returns 2489.824 (round up)
profits.toFixed(2) //returns 2489.82
profits.toFixed(7) //returns 2489.8237000 (padding)
Displaying any number in currency format can't get any easier!

Number.toPrecision()

To toPrecision() now:
var anumber=123.45
anumber.toPrecision(6) //returns 123.450 (padding)
anumber.toPrecision(4) //returns 123.5 (round up)
anumber.toPrecision(2) //returns 1.2e+2 (you figure it out!)
toPrecision() is useful if your number must be of a certain length.

Browser considerations

Now, as noted, our two heros above are JavaScript 1.5 methods. What this means is that they'll only work in IE5.5+ and NS6+. The issue of legacy browsers not performing the desired formatting operation not withstanding, how do you ensure that these two methods at least degrade well? Well, by using method detection in your code. For example:
var profits=2489.8237
if (profits.toFixed) //if browser supports toFixed() method
profits.toFixed(2)
For those of you who also need to ensure legacy browsers such as IE5 also perform the desired number formatting operation, well, then it's time to roll your own function. But be warned, it won't as pretty as what has taken place here!

No comments:

Post a Comment