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

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2010-04-15T14:54:51Z Indexed on 2010/04/15 15:03 UTC
Read the original article Hit count: 421

Filed under:

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>

© Stack Overflow or respective owner

Related posts about jQuery