DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Roger has posted 34 posts at DZone. View Full User Profile

Commafy A Number

09.10.2008
| 2430 views |
  • submit to reddit
        // 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;
}
    

Comments

Snippets Manager replied on Sun, 2009/03/01 - 8:43pm

If parameter (i.e., number) is a simple number (e.g., commafyNumber( 123456789 ) Then number.replace is invalid... ---------------------------------------------------------------------- function commafyNumber( number ) { var withcommas = ( number + '' ).replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) { return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,") }) return withcommas } ----------------------------------------------------------------------