how to print number with commas as thousands separators in Javascript

Posted by mikez302 on Stack Overflow See other posts from Stack Overflow or by mikez302
Published on 2010-05-24T23:42:31Z Indexed on 2010/05/24 23:51 UTC
Read the original article Hit count: 181

Filed under:

I am trying to print an integer in Javascript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this? Here is how I am doing it:

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

I am wondering if anyone has a simpler or more elegant idea. It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas.

© Stack Overflow or respective owner

Related posts about JavaScript