3

Possible Duplicate:
how to print number with commas as thousands separators in Javascript

I have a function that will add thousand seperators to a number, however it is not working well when a decimal is passed in:

function thousandSep(val) {
        return String(val).split("").reverse().join("")
                      .replace(/(.{3}\B)/g, "$1,")
                      .split("").reverse().join("");
    }

If I pass in 10000, I get 10,000 as expected.

However, passing in 10,000.00 I get 1,000,0.00.

How can I modify the function to handle decimals?

Community
  • 1
  • 1
Alan Shortis
  • 1,277
  • 3
  • 18
  • 35

2 Answers2

7

Don't use ., use \d

function thousandSep(val) {
    return String(val).split("").reverse().join("")
                  .replace(/(\d{3}\B)/g, "$1,")
                  .split("").reverse().join("");
}
Joe
  • 80,724
  • 18
  • 127
  • 145
4
function format(n, sep, decimals) {
    sep = sep || "."; // Default to period as decimal separator
    decimals = decimals || 2; // Default to 2 decimals

    return n.toLocaleString().split(sep)[0]
        + sep
        + n.toFixed(decimals).split(sep)[1];
}

format(4567354.677623); // 4,567,354.68
flavian
  • 28,161
  • 11
  • 65
  • 105
  • I like the simplicity of this approach! Although `toLocaleString()` can be funny... For me, it doesn't calculate precision any further than 3 decimal places (at least on Chrome 39.0.2171.95 in the US). For ex, 1111.9998 becomes "1,112". So, if I use `format(4567354.9998, '.', 4))` from your code I get "4,567,355.9998" – dooleyo Dec 23 '14 at 18:39