December 2008 Archive

Another js function to insert commas in numbers

By Luke Smith on December 14, 2008 9:52 PM

This evening's academic exercise was to write your basic 1234 => 1,234 function as terse as possible, and without a loop. At first I thought I could do it with just a clever regex, and maybe I could have, but I abandoned that approach.

This is what I ended up with:

function formatNumber(n) {
    if (!isFinite(n)) {
        return n;
    }

    var s = ""+n, abs = Math.abs(n), _, i;

    if (abs >= 1000) {
        _  = (""+abs).split(/\./);
        i  = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
               _[0].slice(i).replace(/(\d{3})/g,',$1');

        s = _.join('.');
    }

    return s;
}

I could have omitted the storage of Math.abs(n) and the short circuit for numbers not needing comma injection, but eh. No need to sacrifice runtime performance for a few characters.

The basic principle is to use string replace to insert commas on only the chunk of the number that needs them. intAsString.length % 3 || 3; will return the index of the first character that needs a comma before it (for positive values, hence the abs), so everything beyond that point needs to be divided into three digit chunks, each preceded by a comma.

Update - 1/16/2009

I happened across a similar function, based on PHP's number_format function. It prompted me to adapt in the extra params to support precision and specified characters for decimal and thousands divider.

I put the result in a gist. I put together this page to confirm they were behaving comparably.

Update - 3/18/2009

Updated to account for input 1000. > should have been >= Oops! Thanks to Simon for helping me notice that :)

I also put the barebones function in a gist

ls.n

LucasSmith.name

Luke and Liam

I'm Luke. I am a front end engineer at Yahoo! on the YUI team.

Mostly I write about code stuff, but occassionally I'll mix in some real life. You've been warned.

Archives

Tags

Feeds

Subscribe to feed Recent entries

Content licensed under Creative Commons

Code licensed under BSD license

©2005 - 2010 Lucas Smith

Powered by Movable Type