Add comma to numbers every three digits
Asked Answered
M

15

185

How can I format numbers using a comma separator every three digits using jQuery?

For example:

╔═══════════╦═════════════╗
║   Input   ║   Output    ║
╠═══════════╬═════════════╣
║       298 ║         298 ║
║      2984 ║       2,984 ║
║ 297312984 ║ 297,312,984 ║
╚═══════════╩═════════════╝
Mice answered 2/1, 2010 at 3:26 Comment(3)
I am new to jQuery and would like a simple function/plugin that just adds comma after every three digits if numbers are more than three digits long. Positive numbers only, no fractions, no decimals, no currency involved, and standard U.S. format (1,111) not ($1,111 or $1,111.11). I would rather having done using jQuery and not just javascript if possible and would be nice set the code set to a function so it can be applied very easily. How do I go about doing that? Appreciate everyone's input. Thanks again.Mice
@unknown: You already have many answers. Look at the answers you have received and evaluate them to see which is best for you. If you need more clarification for one of the answers, post it as a comment to that answer.Jean
Sorry my question was not concise enough but see Doug Neiner plugin format using Paul Creasey's code for the answer.Mice
E
27

2016 Answer:

Javascript has this function, so no need for Jquery.

yournumber.toLocaleString("en");
Easing answered 17/2, 2016 at 0:58 Comment(3)
Will this work on all browsers? It is working fine on chrome. Will it work on IE9+ & opera, safari ?Involucre
@Involucre w3schools.com/jsref/jsref_tolocalestring.asp supports all browsersSocialize
Just make sure the number you call it on is a number type (int, float, etc..) and not a string.Vagarious
M
264

@Paul Creasey had the simplest solution as the regex, but here it is as a simple jQuery plugin:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

You could then use it like this:

$("span.numbers").digits();
Minute answered 2/1, 2010 at 4:18 Comment(9)
Works perfectly! Thanks to Paul Creasey for simply, elegant code and thanks to Doug Neiner for putting it in plugin format. Credit given to both.Mice
RC @Mark Byers The syntax is right. '999.9999'.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") returns '999.9,999' though.Stead
@Stead the OP didn't update his question, but he did add this comment "Positive numbers only, no fractions, no decimals, no currency involved, and standard U.S. format" which @Paul Creasey's answer provided.Minute
Made a slight mod for input fields: $.fn.digits = function(){ return this.each(function(){ $(this).val( $(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); }) } Gesticulation
I think this would be better suited to a jQuery name-spaced utility style function, e.g. $.digits = function() { ... };.Pitiful
The fastest way is number.toLocaleString("en");Enchanting
function addCommas(t) {return String(t).replace(/(\d)(?=(\d{3})+$)/g, "$1,")}. source: http://icompile.eladkarako.com/javascript-snippet-add-commas-to-number-by-regular-expression/Cultivation
javvascript has a function for this.....<script>document.write(num.toLocaleString("en-US"));</script>Smile
For some reason, this method added 1 to my total. But using number.toLocaleString("en"); worked perfectly.Ambassador
M
134

You could use Number.toLocaleString():

var number = 1557564534;
document.body.innerHTML = number.toLocaleString();
// 1,557,564,534
Member answered 8/1, 2016 at 7:16 Comment(3)
I've try it, but not working on live server, but working on localhost..Mohler
@eladsilver w3schools.com/jsref/jsref_tolocalestring.asp in all browsersSocialize
This worked the easiest for me. I needed currency and commas. I was able to set properties as well: var n = 26787.89 var myObjCurrency = { style: "currency", currency: "USD", currencyDisplay : "symbol" } n.toLocaleString("en-US", myObjCurrency));Deianira
K
82

Something like this if you're into regex, not sure of the exact syntax for the replace tho!

MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
Kayne answered 2/1, 2010 at 3:50 Comment(2)
The syntax is right. '999.9999'.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") returns '999.9,999' though.Jean
@Unknown, I moved it to an answer. It is farther down on this page with usage example.Minute
J
27

You could try NumberFormatter.

$(this).format({format:"#,###.00", locale:"us"});

It also supports different locales, including of course US.

Here's a very simplified example of how to use it:

<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="jquery.numberformatter.js"></script>
        <script>
        $(document).ready(function() {
            $(".numbers").each(function() {
                $(this).format({format:"#,###", locale:"us"});
            });
        });
        </script>
    </head>
    <body>
        <div class="numbers">1000</div>
        <div class="numbers">2000000</div>
    </body>
</html>

Output:

1,000
2,000,000
Jean answered 2/1, 2010 at 3:33 Comment(3)
I took a glance at this plugin and from author description, it was meant to be used in form input fields. How can I adopt it to be applied to <span class="numbers">2984</span> so it formats to <span class="numbers">2,984</span> without decimals. I tried $('span.numbers').format({format:"#,###", locale:"us"}); but nothing happend. Still examing plugin, playing around with it. Sorry I am a jQuery newbie :-)Mice
+1 Great to know about this plugin. I agree that for growth and future internationalization, this would be the best route to follow.Minute
Here is the link to its GitHub repo. github.com/hardhub/jquery-numberformatterSchweiker
W
27

Use function Number();

$(function() {

  var price1 = 1000;
  var price2 = 500000;
  var price3 = 15245000;

  $("span#s1").html(Number(price1).toLocaleString('en'));
  $("span#s2").html(Number(price2).toLocaleString('en'));
  $("span#s3").html(Number(price3).toLocaleString('en'));

  console.log(Number(price).toLocaleString('en'));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<span id="s1"></span><br />
<span id="s2"></span><br />
<span id="s3"></span><br />
Wicklund answered 8/7, 2015 at 7:28 Comment(1)
Thanks, I used your answer. It might be worth noting that this only supports numbers up to 15 digits in length.Accentuation
E
27

2016 Answer:

Javascript has this function, so no need for Jquery.

yournumber.toLocaleString("en");
Easing answered 17/2, 2016 at 0:58 Comment(3)
Will this work on all browsers? It is working fine on chrome. Will it work on IE9+ & opera, safari ?Involucre
@Involucre w3schools.com/jsref/jsref_tolocalestring.asp supports all browsersSocialize
Just make sure the number you call it on is a number type (int, float, etc..) and not a string.Vagarious
R
24

This is not jQuery, but it works for me. Taken from this site.

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;
}
Rota answered 2/1, 2010 at 3:45 Comment(4)
Very "roots" of you :)Cristicristian
"Rootsy" it may be, but I don't think the other fancy-pants approaches would have worked in my situation, where the data is embedded in a Canvas (Chart.JS). But adding that function and calling it in the chart's afterDraw() event works perfectly: ctx.fillText(addCommas(dataset.data[i]),Raddie
This does not work for example 3000000 (7 digits). only for 6 and fewer digits !Macromolecule
clever but would rather just use a lib to this for me..Salts
G
17

A more thorough solution

The core of this is the replace call. So far, I don't think any of the proposed solutions handle all of the following cases:

  • Integers: 1000 => '1,000'
  • Strings: '1000' => '1,000'
  • For strings:
    • Preserves zeros after decimal: 10000.00 => '10,000.00'
    • Discards leading zeros before decimal: '01000.00 => '1,000.00'
    • Does not add commas after decimal: '1000.00000' => '1,000.00000'
    • Preserves leading - or +: '-1000.0000' => '-1,000.000'
    • Returns, unmodified, strings containing non-digits: '1000k' => '1000k'

The following function does all of the above.

addCommas = function(input){
  // If the regex doesn't match, `replace` returns the string unmodified
  return (input.toString()).replace(
    // Each parentheses group (or 'capture') in this regex becomes an argument 
    // to the function; in this case, every argument after 'match'
    /^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {

      // Less obtrusive than adding 'reverse' method on all strings
      var reverseString = function(string) { return string.split('').reverse().join(''); };

      // Insert commas every three characters from the right
      var insertCommas  = function(string) { 

        // Reverse, because it's easier to do things from the left
        var reversed           = reverseString(string);

        // Add commas every three characters
        var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');

        // Reverse again (back to normal)
        return reverseString(reversedWithCommas);
      };

      // If there was no decimal, the last capture grabs the final digit, so
      // we have to put it back together with the 'before' substring
      return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
    }
  );
};

You could use it in a jQuery plugin like this:

$.fn.addCommas = function() {
  $(this).each(function(){
    $(this).text(addCommas($(this).text()));
  });
};
Gnu answered 22/6, 2012 at 10:56 Comment(0)
M
11

Very Easy way is to use toLocaleString() function

tot = Rs.1402598 //Result : Rs.1402598

tot.toLocaleString() //Result : Rs.1,402,598

Updated : 23/01/2021

The Variable Should be in number format. Example :

Number(tot).toLocaleString() //Result : Rs.1,402,598
Melanson answered 27/8, 2019 at 15:45 Comment(0)
S
9

You can also look at the jquery FormatCurrency plugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.

$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });
Stead answered 2/1, 2010 at 3:45 Comment(1)
this question modivated me to release v1.3 of this plugin, so thanksStead
O
5

Here is my javascript, tested on firefox and chrome only

<html>
<header>
<script>
    function addCommas(str){
        return str.replace(/^0+/, '').replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function test(){
        var val = document.getElementById('test').value;
        document.getElementById('test').value = addCommas(val);
    }
</script>
</header>
<body>
<input id="test" onkeyup="test();">
</body>
</html>
Obadias answered 3/1, 2019 at 6:59 Comment(0)
C
2
function formatNumberCapture () {
$('#input_id').on('keyup', function () {
    $(this).val(function(index, value) {
        return value
            .replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            ;
    });
});

You can try this, it works for me

Cheju answered 17/7, 2020 at 14:2 Comment(0)
N
0

use this code to add only number and add comma after three digit in input text from jquery:

$(".allow-numeric-addcomma").on("keypress  blur", function (e) {
   return false; 
});

$(".allow-numeric-addcomma").on("keyup", function (e) {

    var charCode = (e.which) ? e.which : e.keyCode
if (String.fromCharCode(charCode).match(/[^0-9]/g))
    return false;

value = $(this).val().replace(/,/g, '') + e.key;
var nStr = value + '';
nStr = nStr.replace(/\,/g, "");
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');
}

$(this).val(x1 + x2);
return false;
});
Nika answered 26/12, 2021 at 7:9 Comment(0)
C
0

This code work for me

 function checkPrice() {
                    $('input.digits').keyup(function (event) {
                        // skip for arrow keys
                        if (event.which >= 37 && event.which <= 40) {
                            event.preventDefault();
                        }
                        var $this = $(this);
                        var num = $this.val().replace(/,/g, '');
                        // the following line has been simplified. Revision history contains original.
                        $this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
                    });
                }

Your texbox sample

<input type="text" name="price" id="price" class="form-control digits" onkeyup="checkPrice()"  >
Cecelia answered 3/8, 2022 at 7:15 Comment(0)
F
0
var num = 1234567.89;

var commas = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Feminine answered 26/4, 2023 at 14:55 Comment(1)
Feel free to add more context to improve your answer to the original question.Ponton

© 2022 - 2024 — McMap. All rights reserved.