Add a thousands separator to a total with Javascript or jQuery?
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];
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