I use JS to sum values from entries made by a user on a form.
Then JS return the value with two decimals. However, I would like it to be separated every 1,000.00 with a comma. I am new to programming and have tried several methods. This is my code so far:
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2).replace(',', ''));
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
/* Don't add commas until you complete the additions- commas as thousands separators are for strings of digits, not numbers. */ addCommas(123456789.75)
// returned value: (String) 123,456,789.75
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
/* Don't add commas until you complete the additions- commas as thousands separators are for strings of digits, not numbers. */ addCommas(123456789.75)
// returned value: (String) 123,456,789.75
Thank you mrhoo,
However, how do I apply the addCommas function to my sum value which should be displayed in the <span>?
Bookmarks