How to format numbers in JavaScript flexibly and efficiently

This article continues my series on parsing and formatting data with JavaScript, this time with numeric data. I don’t need to do number parsing, but formatting is very useful. The technique is similar to my date formatting code – code that writes code (for raw speed), using custom format specifier strings (for flexibility and ease of use). The result is number formatting functionality that is highly efficient, flexible, and easy to use.

First, the idea: you have a number, you want it formatted a certain way. Here’s how:

var dollars = 5.001;
// result: "$5.00"
var percent = .08134;
// result: "8.13%"
var bignum = 12831242485472;
alert(bignum.numberFormat("0,0,, million");
// result: "12,831,243 million"

My custom date formatting code used PHP’s date-formatting syntax because it’s much less context-sensitive and (I think) more useful than Microsoft’s, but my number-formatting syntax is similar to Microsoft’s because it’s much more widely used and I don’t see an existing, better alternative. Rather than documenting it separately, I’ll just point you to the (poor quality) Microsoft documentation for the .NET Custom Numeric Format Strings functionality, and list the differences from my implementation:

I’ve only implemented a subset of the various number-formatting syntaxes I’ve seen in spreadsheets and so forth. The subset is about 85% complete in my opinion. However, I think it’s functionally about 99% complete, which means I think 99% of the time you want to format a number, it will do what you want. The tradeoff is simplicity and speed. Number formatting is actually much more difficult than date formatting, and I’ve tried to keep the code sane.

I have a set of unit tests, which use the excellent JsUnit library. Bring up the unit test page and enter the following url to be tested:

Of course there’s the obligatory demo page, too.