Number Formatting in Javascript


I released my little Firefox Counter widget, and within two weeks the feed changed to remove the thousands separators (commas, the U.S. and British convention). With over 70 million downloads of Firefox now, it's a big number to view without such separators. Javascript to the rescue...



Tjalling Kikkert wrote from the Netherlands to suggest a solution, a simple bit of Javascript using regular expressions to re-insert the missing thousands separators. Tjalling's suggestion used periods or "full stops" as thousands separators.

A little casual research showed me that displaying integers to a global audience was going to take a bit more thought than just changing the character for the thousands separator. In India, for example, the digits are comma separated, but the lowest three digits are grouped together, and after that every 2 digits are grouped together... so 123,456,789 (U.S./British) becomes 12,34,56,789. In Japan and China digits are grouped by fours with ten-thousands separated by ideographs, so the same number is written as 1 2345 6789.

The only example I could find that attempted something like this made rather liberal use of regular expressions and didn't handle the Indian case. Here's a quote I love by Jamie Zawinski, posted to comp.emacs.xemacs: "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." That about sums up my feelings, too. Regular expressions are very powerful, but a pain in the neck to get right and troubleshoot.

Here I just wanted to format some integers of limited size. It's a simple problem, solvable by a much simpler approach. What I came up with is actually inspired by the way Forth handled numeric formatting, though the details are quite different and the output pattern isn't backwards. Feel free to make use of it in any free or commercial project, with or without giving me credit. If you come up with improvements, though, I'd appreciate it if you could drop me a note to help me improve my code.

Here's the code: FormatInteger.js

In case it isn't obvious, my code picks one of the patterns from the aptly named patterns array and passes the pattern to the formatInteger() function along with the integer string to be formatted. Another bit of Javascript dynamically builds a select element in the XHTML document, so all I need to do to support a new integer format is to append its pattern to the patterns array. Simple and clean, with nary a regular expression in sight.

Posted: Sat - July 16, 2005 at 12:52 AM          


©