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 thou
a recursive solution:
function thousands(amount) {
if( /\d{3}\d+/.test(amount) ) {
return thousands(amount.replace(/(\d{3}?)(,|$)/, ',$&'));
}
return amount;
}
another split solution:
function thousands (amount) {
return amount
// reverse string
.split('')
.reverse()
.join('')
// grouping starting by units
.replace(/\d{3}/g, '$&,')
// reverse string again
.split('')
.reverse()
.join('');
}
Below is the working Example:
$("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
This line is sufficient, it works for me. Check the complete code below. Let me know if it works fine for you too.
$(".action.showcart").on('click', function() {
var miniCartTotal = $("#estimated-subtotal .price").html();
var miniCartTotalString = miniCartTotal.replace(/\$/g, '');
var miniCartTotalString = miniCartTotalString.replace(/,/g, '');
var configValue = 5;
miniCartTotal = parseFloat(miniCartTotalString) + configValue;
console.log("updated value " + miniCartTotal);
$("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$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;
}
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];
This is how I do it:
// 2056776401.50 = 2,056,776,401.50
function humanizeNumber(n) {
n = n.toString()
while (true) {
var n2 = n.replace(/(\d)(\d{3})($|,|\.)/g, '$1,$2$3')
if (n == n2) break
n = n2
}
return n
}
Or, in CoffeeScript:
# 2056776401.50 = 2,056,776,401.50
humanizeNumber = (n) ->
n = n.toString()
while true
n2 = n.replace /(\d)(\d{3})($|,|\.)/g, '$1,$2$3'
if n == n2 then break else n = n2
n
Use toLocaleString()
In your case do:
return "Total Pounds Entered : " + tot.toLocaleString();