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>
To comma-separate thousands in a big number in JavaScript, use the built-in toLocaleString() method. It localizes the number to follow a country-specific number formatting. To separate thousands with commas, localize the number to the USA.
It needs to add x1=x1. replace(\,\g,'') to work correctly when the user changes the number.
Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With