Add a thousands separator to a total with Javascript or jQuery?

I have a function that sums a column of data in an html table. It does so admirably only I would like to have it put the commas in there that are needed to separate the thousands. Initially, you'll note, there are commas in the numbers being added. So that the function will add them, they are removed. How do I add the commas back in there?

<script type="text/javascript">
    function sumOfColumns(tableID, columnIndex, hasHeader) {
        var tot = 0;
        $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
          .children("td:nth-child(" + columnIndex + ")")
          .each(function() {
              tot += parseInt($(this).html().replace(',', ''));
          });
        return "Total Pounds Entered : " + tot;
    }
</script>

The $(this).html().replace(',', '') shouldn't actually modify the page. Are you sure the commas are being removed in the page?

If it is, this addCommas function should do the trick.

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Use toLocaleString()
In your case do:

return "Total Pounds Entered : " + tot.toLocaleString(); 

toLocaleString() method's syntax looks like:

toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)

If your browser can't work with toLocaleString() you can try use locales argument, for example:

var number = 123456.789;

// German uses comma as decimal separator and period for thousands
console.log(number.toLocaleString('de-DE'));
// → 123.456,789

Full documentation available here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString


This will add thousand separators while retaining the decimal part of a given number:

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

You could also probe for the locale's decimal separator with:

var sep = (0).toFixed(1)[1];

Seems like this is ought to be the approved answer...

Intl.NumberFormat('en-US').format(count)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat