[jquery] Add a thousands separator to a total with Javascript or 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>

This question is related to jquery

The answer is


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


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

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

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


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

Use:

numberWithCommas(200000);

==> 200,000


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

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

Use toLocaleString()
In your case do:

return "Total Pounds Entered : " + tot.toLocaleString(); 

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.


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.


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.