Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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> 
like image 846
Matt Avatar asked Apr 15 '10 14:04

Matt


People also ask

How do you split thousands in JavaScript?

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.

How do you add a thousand separator in HTML?

It needs to add x1=x1. replace(\,\g,'') to work correctly when the user changes the number.

How do you change a thousand separator in numbers?

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.


1 Answers

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; } 
like image 84
dave1010 Avatar answered Sep 21 '22 13:09

dave1010