Over a million developers have joined DZone.

Commafy A Number

·
// function commafyNumber - Adds commas to a
//     non-commaed number. For instance,
//     1000000 becomes 1,000,000.
//     I did not write this original function: it comes
//     from Steve Levithan's blog:
//         http://blog.stevenlevithan.com/archives/commafy-numbers
//       (...but it's too useful not to snip)


function commafyNumber(number) {
    var withcommas;
    withcommas = number.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
        var inter;
        inter = $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
        return inter;
    });
    return withcommas;
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}