English 中文(简体)
Add comma to numbers every three digits
原标题:

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 ║
╚═══════════╩═════════════╝
最佳回答

2016 Answer:

Javascript has this function, so no need for Jquery.

yournumber.toLocaleString("en");
问题回答

@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)(?=(ddd)+(?!d))/g, "$1,") ); 
    })
}

You could then use it like this:

$("span.numbers").digits();

You could use Number.toLocaleString():

var number = 1557564534;
document.body.innerHTML = number.toLocaleString();
// 1,557,564,534

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

MyNumberAsString.replace(/(d)(?=(ddd)+(?!d))/g, "$1,");

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

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 />

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

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

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

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

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

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

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()"  >
var num = 1234567.89;

var commas = num.toString().replace(/B(?=(d{3})+(?!d))/g, ",");




相关问题
getGridParam is not a function

The HTML: <a href="javascript:void(0)" id="m1">Get Selected id s</a> The Function: jQuery("#m1").click( function() { var s; s = jQuery("#list4").getGridParam( selarrrow )...

selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

jQuery cycle page with links

I am using the cycle plugin with pager functionality like this : $j( #homebox ) .cycle({ fx: fade , speed: fast , timeout: 9000, pager: #home-thumbs , ...

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

jConfirm with this existing code

I need help to use jConfirm with this existing code (php & Jquery & jAlert). function logout() { if (confirm("Do you really want to logout?")) window.location.href = "logout.php"; } ...

Wrap text after particular symbol with jQuery

What I m trying to do, is wrap text into div inside ll tag. It wouldn t be a problem, but I need to wrap text that appears particularly after "-" (minus) including "minus" itself. This is my html: &...

热门标签