53

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>
Matt
  • 5,542
  • 14
  • 48
  • 59

12 Answers12

94

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;
}
dave1010
  • 15,135
  • 7
  • 67
  • 64
  • 3
    [I made a *slightly* more foolproof version that checks if nStr is actually a number.](https://github.com/Blacksilver42/website-scripts/blob/master/thousep2.js) – SIGSTACKFAULT Oct 15 '17 at 19:10
39

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

ekimas
  • 393
  • 5
  • 10
Greg Valcourt
  • 691
  • 6
  • 13
  • Delightfully simple, but not yet widely supported by browsers. :( – Niels B. May 04 '15 at 19:26
  • I can't use it bacause it's dependent on browser locale. Great function otherwise. – StaNov May 20 '15 at 06:55
  • Note: This method is dependant on your locale and might not separate by commas if thats what you need. [See MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) – hitautodestruct Jun 24 '20 at 08:23
  • This post may help. https://stackoverflow.com/questions/31581011/how-to-use-tolocalestring-and-tofixed2-in-javascript var num = 2046430; num.toLocaleString(undefined, {minimumFractionDigits: 2}) – Lakshitha Kanchana Jan 04 '23 at 03:24
21

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];
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
  • toLocaleString only works on Date objects: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date/toLocaleString – dave1010 Apr 15 '10 at 15:29
  • toLocaleString doesn't add thousand separators. Tested on Firefox 3.5.9 / Snow Leopard. – ibz Apr 29 '10 at 11:01
  • @dave1010: You're wrong: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Number/ToLocaleString – Ates Goral Apr 30 '10 at 15:19
  • 1
    @ibz: I guess it depends on your locale. It adds it in my locale (US English.) The question seems to be related to this locale as well. What's your locale? – Ates Goral Apr 30 '10 at 15:22
  • toLocaleString() does not add thousands separators and is often identical to toString(). – danorton Sep 20 '11 at 01:00
  • 2
    @danorton: *sigh*... As I mentioned earlier, it depends on _your locale_. But it also seems to depends on the browser. FF6, with English (Canada) locale on Windows adds the comma for me. `(4000).toLocaleString() === "4,000"`. Come over and see for yourself if you still don't believe me :( – Ates Goral Sep 20 '11 at 04:38
  • 1
    @Ates Yes, it does work in FF depending on locale, but that behavior is non-standard - in Chrome it returns "4000", and IE will return "4,000.00" instead. – Tamzin Blake Apr 09 '12 at 14:10
  • 2
    This returns the expected result in Chrome (March 2013) on a US locale comp. If browser support is there, this is obviously the ideal for most usage, since number separation is very much a locale issue (comma = decimal and group separator = space for, I'm pretty sure, most of the world). However the line 'decimals = decimals || 2;' is an error. Zero is a reasonable value for the decimals argument but it evaluates to false, so you get 2 instead of 0. – Semicolon Mar 20 '13 at 14:44
  • The simplest and generic function! – Nay Oct 26 '19 at 02:15
9

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

chad steele
  • 828
  • 9
  • 13
  • 2
    Thx for this answer - should have more upvotes! Compatiblity is alsop good, even IE can handle this (partial) ;) – user2345998 Jun 03 '20 at 07:06
  • when I type number like "71500" in input and tried to format it as it type, it stuck in "7.150". It couldn't format big number I think or there's another setup or something idk. – Fahmi Jan 08 '22 at 14:26
  • @Fahmi please provide your syntax. It sounds like you're not using 'en-US' , but I can't help without seeing your code. – chad steele Jan 10 '22 at 16:59
  • @chad steele hi I apologize for that, I used input number component from ant design vue to format the number in the input field, I think the component just ruined it or something. I use 'id-ID' locale or 'en-GB'. I fixed it by not using the component . sorry – Fahmi Jan 14 '22 at 13:13
6
<script>
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>

Use:

numberWithCommas(200000);

==> 200,000

Jay Nguyễn
  • 82
  • 1
  • 5
3

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.

El Gucs
  • 897
  • 9
  • 18
2

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.

Adam Marshall
  • 693
  • 6
  • 16
2

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
stefansundin
  • 2,826
  • 1
  • 20
  • 28
2

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.

dkellner
  • 8,726
  • 2
  • 49
  • 47
2

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

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

Khalid Habib
  • 1,100
  • 1
  • 16
  • 25
-1

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('');
}
  • This does not work btw. It adds commas in front of numbers, for example 456 becomes ",456". – Johncl Jan 20 '17 at 10:10