86

I have these numbers

10999 and 8094 and 456

And all i want to do is add a comma in the right place if it needs it so it looks like this

10,999 and 8,094 and 456

These are all within a p tag like this <p class="points">10999</p> etc.

Can it be done?

I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/ but can't seem to get it to work

Thanks

Jamie

UPDATE

Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/

Going to look at the new Globalization plugin for a better way of doing it

Thanks

Jamie

Jamie Taylor
  • 3,500
  • 21
  • 65
  • 99
  • 4
    Related question here: http://stackoverflow.com/questions/2901102/how-to-print-number-with-commas-as-thousands-separators-in-javascript – epascarello Oct 07 '10 at 15:46
  • 3
    +1 for your fiddle. You should include your solution in your update: ```.replace(/\B(?=(?:\d{3})+(?!\d))/g, ',')``` – zhon Oct 07 '13 at 23:32
  • 2
    I wish I could +100 for your solution: Regex saying Not word boundary followed by a positive look ahead of 3 digits possibly repeated not followed by a digit. Awesome! – zhon Oct 07 '13 at 23:54
  • This solution was the best for the most part, but didn't quite work for me. Unfortunately I need to display numbers with 4 and sometimes 5 decimal places. The people I work for deal with high-transaction count and fractions of a penny add up to $100s or $1000s of dollars (think Office Space). I just slapped some code on your fiddle to allow it to handle decimal places past 3: [http://jsfiddle.net/W5jwY/554/](http://jsfiddle.net/W5jwY/554/) – Josh Bilderback Oct 21 '15 at 16:19
  • Real answer to this question here: https://stackoverflow.com/a/2632502/1860982 – Tosin Onikute May 19 '18 at 17:28

11 Answers11

145

Works on all browsers, this is all you need.

  function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
    }
    return val;
  }

Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:

$('#elementID').html(commaSeparateNumber(1234567890));

or

$('#inputID').val(commaSeparateNumber(1234567890));

However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to @baacke in the comments.

  function commaSeparateNumber(val){
   val = val.toString().replace(/,/g, ''); //remove existing commas first
   var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
   var valSplit = valRZ.split('.'); //then separate decimals
    
   while (/(\d+)(\d{3})/.test(valSplit[0].toString())){
    valSplit[0] = valSplit[0].toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
   }

   if(valSplit.length == 2){ //if there were decimals
    val = valSplit[0] + "." + valSplit[1]; //add decimals back
   }else{
    val = valSplit[0]; }

   return val;
  }

And in your jQuery, use like so:

$('.your-element').each(function(){
  $(this).html(commaSeparateNumber($(this).html()));
});

Here's the jsFiddle.

Urget
  • 17
  • 1
  • 9
Timothy Perez
  • 20,154
  • 8
  • 51
  • 39
  • 4
    user1655655's answer is way better – Pyrolistical Jan 12 '14 at 22:17
  • 7
    Two issues with this answer: 1. Calling the function more than once with the same value will result in commas in the wrong places (for example, keyup events). 2. This function does not handle decimals properly and will add commas inside the decimals. See this [JSFiddle](http://jsfiddle.net/baacke/XL5dn/) for a modified version that fixes both. – baacke Feb 13 '14 at 20:07
  • 1
    @baacke The idea of this function is to be slim, so I didn't account for calling it twice on a the same var or decimals (since it wasn't in the question). Either way, your fiddle example is useful for cases where you would need a decimal so thank you. – Timothy Perez Feb 19 '14 at 15:38
  • Where a comma or period appears is determined by locale. The JS standard library can already do this for you. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString – Alex Harvey Jul 02 '15 at 15:12
135
Number(10000).toLocaleString('en');  // "10,000"
aboutaaron
  • 4,869
  • 3
  • 36
  • 30
sonnenhaft
  • 1,638
  • 1
  • 13
  • 15
  • 6
    This is the most simple solution and it work perfect for me. Thank you! – ahgood Sep 28 '13 at 15:15
  • 3
    thank you for that hint, much better than writing custom functions or including a plugin. for me answer #1! – linqu Dec 19 '13 at 13:52
  • 5
    This is great, and works in most desktop browsers, but beware it's limited support in mobile browsers right now... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_Compatibility – Luke Jan 15 '14 at 05:22
  • 2
    For anybody looking to use this with Node.js, it won't work unless you re-compile the v8 engine to include i18n: http://stackoverflow.com/questions/23571043/ecmascript-internationalization-api-with-node/23571981 – Tom Spencer Jan 28 '15 at 12:42
  • 2
    Try this `Number(012).toLocaleString('en')` :| – Aamir Afridi Mar 19 '15 at 15:53
  • Clever technique if number doesn't have a leading zero and browser support doesn't precede IE11. – Fillip Peyton Mar 26 '15 at 17:00
  • 3
    This is inconsistent across browsers and doesn't work at all on iPad. – Isaac Askew Mar 29 '15 at 22:10
  • 1
    @FillipPeyton If you're worried about the leading-zero case, just do `Number("012").toLocaleString("en");` (in other words, provide the number as a string rather than a number literal -- which is how you'd usually use it anyway) – Venryx May 13 '17 at 11:07
  • Note that if the number has a decimal portion, this approach will trim the decimal portion to only the first 3 digits. If you want to keep the decimal portion untouched, split it into the integer and fractional parts, and only change the integer part. Example: https://jsfiddle.net/tqb4x8dp/ – Venryx May 13 '17 at 11:11
  • The best solution without doing custom things – Murtaza JAFARI Mar 30 '21 at 07:31
3

Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.

      $('#textfield').live('keyup', function (event) {
        var value=$('#textfield').val();

      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var newvalue=value.replace(/,/g, '');   
      var valuewithcomma=Number(newvalue).toLocaleString('en');   
      $('#textfield').val(valuewithcomma); 

      });

    <form><input type="text" id="textfield" ></form>
Tosin Onikute
  • 3,883
  • 6
  • 38
  • 61
1

Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.

adamwdraper
  • 193
  • 3
  • 4
1
    function delimitNumbers(str) {
      return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
        return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
      });
    }

    alert(delimitNumbers(1234567890));
Sumith Harshan
  • 6,325
  • 2
  • 36
  • 35
1

Take a look at recently released Globalization plugin to jQuery by Microsoft

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
0

I'm guessing that you're doing some sort of localization, so have a look at this script.

Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162
0

Using toLocaleString ref at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

function formatComma(value, sep = 0) {
      return Number(value).toLocaleString("ja-JP", { style: "currency", currency: "JPY", minimumFractionDigits: sep });
    }
console.log(formatComma(123456789, 2)); // ¥123,456,789.00
console.log(formatComma(123456789, 0)); // ¥123,456,789
console.log(formatComma(1234, 0)); // ¥1,234
Tính Ngô Quang
  • 4,400
  • 1
  • 33
  • 33
-1

another approach:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
var a  = addCommas(10000.00);
alert(a);

Another amazing plugin: http://www.teamdf.com/web/jquery-number-format/178/

abhiklpm
  • 1,603
  • 2
  • 16
  • 21
-1

Another way to do it:

function addCommas(n){
  var s = "",
      r;

  while (n) {
    r = n % 1000;
    s = r + s;
    n = (n - r)/1000;
    s = (n ? "," : "") + s;
  }

  return s;
}

alert(addCommas(12345678));
theWanderer4865
  • 861
  • 13
  • 20
George
  • 1
-1

Here is my coffeescript version of @baacke's fiddle provided in a comment to @Timothy Perez

class Helpers
    @intComma: (number) ->
        # remove any existing commas
        comma = /,/g
        val = number.toString().replace comma, ''

        # separate the decimals
        valSplit = val.split '.'

        integer = valSplit[0].toString()
        expression = /(\d+)(\d{3})/
        while expression.test(integer)
            withComma = "$1,$2"
            integer = integer.toString().replace expression, withComma

        # recombine with decimals if any
        val = integer
        if valSplit.length == 2
            val = "#{val}.#{valSplit[1]}"

        return val
pymarco
  • 7,807
  • 4
  • 29
  • 40