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

Jquery

Jquery Problem Overview


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>

Jquery Solutions


Solution 1 - Jquery

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;
}

Solution 2 - Jquery

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

Solution 3 - 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];

Solution 4 - Jquery

Seems like this is ought to be the approved answer...

Intl.NumberFormat('en-US').format(count)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

Solution 5 - Jquery

<script>
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>

Use:

numberWithCommas(200000);

==> 200,000

Solution 6 - Jquery

I know this is an uber old post and has good answers, BUT if anyone is interested, there is a jQuery plugin which simplifies number formatting (thousands formatting, number of decimal places, custom thousands separator, etc) by making an include and a simple call. Has lots of features and documentation is enough. It's called jQuery Number.

You just include it:

<script type="text/javascript" src="jquery/jquery.number.min.js"></script>

And then use it:

On an automatic formatting HTML input: $('input.number').number( true, 2 );

or

On a JS call: $.number( 5020.2364, 2 ); // Outputs: 5,020.24

Hopefully this helps someone.

Solution 7 - Jquery

I got somewhere with the following method:

var value = 123456789.9876543 // i.e. some decimal number

var num2 = value.toString().split('.');
var thousands = num2[0].split('').reverse().join('').match(/.{1,3}/g).join(',');
var decimals = (num2[1]) ? '.'+num2[1] : '';

var answer =  thousands.split('').reverse().join('')+decimals;	

Using split-reverse-join is a sneaky way of working from the back of the string to the front, in groups of 3. There may be an easier way to do that, but it felt intuitive.

Solution 8 - Jquery

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

Solution 9 - Jquery

Consider this:

function group1k(s) {
	return (""+s)
		.replace(/(\d+)(\d{3})(\d{3})$/  ,"$1 $2 $3" )
		.replace(/(\d+)(\d{3})$/         ,"$1 $2"    )
		.replace(/(\d+)(\d{3})(\d{3})\./ ,"$1 $2 $3.")
		.replace(/(\d+)(\d{3})\./        ,"$1 $2."   )
	;
}

It's a quick solution for anything under 999.999.999, which is usually enough. I know the drawbacks and I'm not saying this is the ultimate weapon - but it's just as fast as the others above and I find this one more readable. If you don't need decimals you can simplify it even more:

function group1k(s) {
	return (""+s)
		.replace(/(\d+)(\d{3})(\d{3})$/ ,"$1 $2 $3")
		.replace(/(\d+)(\d{3})$/        ,"$1 $2"   )
	;
}

Isn't it handy.

Solution 10 - Jquery

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,"));
});

Solution 11 - Jquery

best and simple way to format the number is to use java-script function

var numberToformat = 1000000000
//add locality here, eg: if you need English currency add 'en' and if you need Danish currency format then use 'da-DA'.
var locality = 'en-EN';
numberToformat = numberToformat.toLocaleString(locality , { 
minimumFractionDigits: 4 })
document.write(numberToformat);

for more information click documentation page

Solution 12 - Jquery

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('');
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - Jquerydave1010View Answer on Stackoverflow
Solution 2 - JqueryGreg ValcourtView Answer on Stackoverflow
Solution 3 - JqueryAtes GoralView Answer on Stackoverflow
Solution 4 - Jquerychad steeleView Answer on Stackoverflow
Solution 5 - JqueryJay NguyễnView Answer on Stackoverflow
Solution 6 - JqueryGusstavv GilView Answer on Stackoverflow
Solution 7 - JqueryAdam MarshallView Answer on Stackoverflow
Solution 8 - JquerystefansundinView Answer on Stackoverflow
Solution 9 - JquerydkellnerView Answer on Stackoverflow
Solution 10 - JquerySuyash Kumar BhartiView Answer on Stackoverflow
Solution 11 - JqueryKhalid HabibView Answer on Stackoverflow
Solution 12 - JqueryJesús GermadeView Answer on Stackoverflow