Javascript Thousand Separator / string format












71















Is there any function in Javascript for formatting number and strings ?



I am looking for a way for thousand separator for string or numbers...
(Like String.Format In c#)










share|improve this question

























  • bytes.com/topic/c-sharp/answers/248039-formatcurrency-equiv

    – bevacqua
    Sep 20 '10 at 16:41











  • I think you'll find what you need in there :) stackoverflow.com/questions/610406/…

    – Jad
    Sep 20 '10 at 16:41











  • How to print a number with commas as thousands separators in JavaScript: stackoverflow.com/questions/2901102/…

    – Adrien Be
    Dec 8 '16 at 15:44











  • with pure javascript + single regex replace stackoverflow.com/a/44324879/681830

    – Val
    Jun 2 '17 at 9:15
















71















Is there any function in Javascript for formatting number and strings ?



I am looking for a way for thousand separator for string or numbers...
(Like String.Format In c#)










share|improve this question

























  • bytes.com/topic/c-sharp/answers/248039-formatcurrency-equiv

    – bevacqua
    Sep 20 '10 at 16:41











  • I think you'll find what you need in there :) stackoverflow.com/questions/610406/…

    – Jad
    Sep 20 '10 at 16:41











  • How to print a number with commas as thousands separators in JavaScript: stackoverflow.com/questions/2901102/…

    – Adrien Be
    Dec 8 '16 at 15:44











  • with pure javascript + single regex replace stackoverflow.com/a/44324879/681830

    – Val
    Jun 2 '17 at 9:15














71












71








71


18






Is there any function in Javascript for formatting number and strings ?



I am looking for a way for thousand separator for string or numbers...
(Like String.Format In c#)










share|improve this question
















Is there any function in Javascript for formatting number and strings ?



I am looking for a way for thousand separator for string or numbers...
(Like String.Format In c#)







javascript string numbers format






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 20 '10 at 18:55









Josh Stodola

64k39166217




64k39166217










asked Sep 20 '10 at 16:35









LostLordLostLord

83982431




83982431













  • bytes.com/topic/c-sharp/answers/248039-formatcurrency-equiv

    – bevacqua
    Sep 20 '10 at 16:41











  • I think you'll find what you need in there :) stackoverflow.com/questions/610406/…

    – Jad
    Sep 20 '10 at 16:41











  • How to print a number with commas as thousands separators in JavaScript: stackoverflow.com/questions/2901102/…

    – Adrien Be
    Dec 8 '16 at 15:44











  • with pure javascript + single regex replace stackoverflow.com/a/44324879/681830

    – Val
    Jun 2 '17 at 9:15



















  • bytes.com/topic/c-sharp/answers/248039-formatcurrency-equiv

    – bevacqua
    Sep 20 '10 at 16:41











  • I think you'll find what you need in there :) stackoverflow.com/questions/610406/…

    – Jad
    Sep 20 '10 at 16:41











  • How to print a number with commas as thousands separators in JavaScript: stackoverflow.com/questions/2901102/…

    – Adrien Be
    Dec 8 '16 at 15:44











  • with pure javascript + single regex replace stackoverflow.com/a/44324879/681830

    – Val
    Jun 2 '17 at 9:15

















bytes.com/topic/c-sharp/answers/248039-formatcurrency-equiv

– bevacqua
Sep 20 '10 at 16:41





bytes.com/topic/c-sharp/answers/248039-formatcurrency-equiv

– bevacqua
Sep 20 '10 at 16:41













I think you'll find what you need in there :) stackoverflow.com/questions/610406/…

– Jad
Sep 20 '10 at 16:41





I think you'll find what you need in there :) stackoverflow.com/questions/610406/…

– Jad
Sep 20 '10 at 16:41













How to print a number with commas as thousands separators in JavaScript: stackoverflow.com/questions/2901102/…

– Adrien Be
Dec 8 '16 at 15:44





How to print a number with commas as thousands separators in JavaScript: stackoverflow.com/questions/2901102/…

– Adrien Be
Dec 8 '16 at 15:44













with pure javascript + single regex replace stackoverflow.com/a/44324879/681830

– Val
Jun 2 '17 at 9:15





with pure javascript + single regex replace stackoverflow.com/a/44324879/681830

– Val
Jun 2 '17 at 9:15












12 Answers
12






active

oldest

votes


















100














Update (7 years later)



The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString



So you can do:



(1234567.89).toLocaleString('en')              // for numeric input
parseFloat("1234567.89").toLocaleString('en') // for string input


The function implemented below works, too, but simply isn't necessary.



(I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)





Original Answer



According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:



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


Edit:
To go the other way (convert string with commas to number), you could do something like this:



parseFloat("1,234,567.89".replace(/,/g,''))





share|improve this answer


























  • Really Really Appreciate It // But How Can i Convert that string (with commas) to a number ?

    – LostLord
    Sep 20 '10 at 16:51











  • this function breaks for numbers greater than 100,000

    – DevZer0
    Apr 28 '15 at 7:27






  • 1





    @DevZer0 no it doesn't

    – Tallboy
    Jan 6 '16 at 2:27











  • I needed "the other" way. works perfectly. Thanks!

    – Erik Kalkoken
    Feb 3 '16 at 15:07











  • Kind of a clumsy solution, but works.

    – Kirill E.
    May 13 '16 at 15:49





















119














If is about localizing thousands separators, delimiters and decimal separators, go with the following:



// --> numObj.toLocaleString( [locales [, options] ] )
parseInt( number ).toLocaleString();


There are several options you can use (and even locales with fallbacks):






number = 123456.7089;

result = parseInt( number ).toLocaleString() + "<br>";
result += number.toLocaleString( 'de-DE' ) + "<br>";
result += number.toLocaleString( 'ar-EG' ) + "<br>";
result += number.toLocaleString( 'ja-JP', {
style : 'currency',
currency : 'JPY',
currencyDisplay : 'symbol',
useGrouping : true
} ) + "<br>";
result += number.toLocaleString( [ 'jav', 'en' ], {
localeMatcher : 'lookup',
style : 'decimal',
minimumIntegerDigits : 2,
minimumFractionDigits : 2,
maximumFractionDigits : 3,
minimumSignificantDigits : 2,
maximumSignificantDigits : 3
} ) + "<br>";

var el = document.getElementById( 'result' );
el.innerHTML = result;

<div id="result"></div>





Details on the MDN info page.



Edit: Commentor @I like Serena adds the following:




To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.







share|improve this answer





















  • 3





    All I can say is wow. Beautiful.

    – pimbrouwers
    Mar 3 '14 at 20:59






  • 12





    +1 for not reinventing the wheel.

    – Mariano Cavallo
    Mar 20 '14 at 14:18






  • 4





    assuming the browser's locale is always what you want...

    – sibidiba
    Apr 15 '14 at 11:09






  • 1





    You're my hero, kaiser.

    – Michael
    Feb 17 '15 at 16:07






  • 2





    To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

    – I like Serena
    Sep 12 '15 at 21:54





















26














Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.






const format = num => {
const n = String(num),
p = n.indexOf('.')
return n.replace(
/d(?=(?:d{3})+(?:.|$))/g,
(m, i) => p < 0 || i < p ? `${m},` : m
)
}

[
format(100), // "100"
format(1000), // "1,000"
format(1e10), // "10,000,000,000"
format(1000.001001) // "1,000.001001"
]
.forEach(n => console.log(n))





» Verbose regex explanation (regex101.com)



flow diagram






share|improve this answer


























  • Has this syntax diagram been created on regex101.com?

    – Gerold Broser
    Apr 19 '17 at 23:26






  • 1





    @GeroldBroser regexper.com

    – Emissary
    Apr 20 '17 at 5:46



















8














There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number



It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:



$.number(12345.4556, 2);          // -> 12,345.46
$.number(12345.4556, 3, ',', ' ') // -> 12 345,456


You can use it inside input fields directly, which is nicer, using same options like above:



$("input").number(true, 2);


Or you can apply to a whole set of DOM elements using selector:



$('span.number').number(true, 2);





share|improve this answer































    4














    // thousand separates a digit-only string using commas
    // by element: onkeyup = "ThousandSeparate(this)"
    // by ID: onkeyup = "ThousandSeparate('txt1','lbl1')"
    function ThousandSeparate()
    {
    if (arguments.length == 1)
    {
    var V = arguments[0].value;
    V = V.replace(/,/g,'');
    var R = new RegExp('(-?[0-9]+)([0-9]{3})');
    while(R.test(V))
    {
    V = V.replace(R, '$1,$2');
    }
    arguments[0].value = V;
    }
    else if ( arguments.length == 2)
    {
    var V = document.getElementById(arguments[0]).value;
    var R = new RegExp('(-?[0-9]+)([0-9]{3})');
    while(R.test(V))
    {
    V = V.replace(R, '$1,$2');
    }
    document.getElementById(arguments[1]).innerHTML = V;
    }
    else return false;
    }





    share|improve this answer

































      3














      I use this:



      function numberWithCommas(number) {
      return number.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
      }


      source: link






      share|improve this answer
























      • '123452343267.0505'.replace(/B(?=(d{3})+(?!d))/g, ","); "123,452,343,267.0,505" - notice that last comma after the decimal point.

        – hippietrail
        Oct 3 '17 at 0:53





















      3














      You can use javascript. below are the code, it will only accept numeric and one dot




      here is the javascript




      <script >

      function FormatCurrency(ctrl) {
      //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
      if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
      return;
      }

      var val = ctrl.value;

      val = val.replace(/,/g, "")
      ctrl.value = "";
      val += '';
      x = val.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');
      }

      ctrl.value = x1 + x2;
      }

      function CheckNumeric() {
      return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
      }

      </script>



      HTML




      <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />


      DEMO JSFIDDLE






      share|improve this answer































        3














        var number = 35002343;

        console.log(number.toLocaleString());


        for the reference you can check here
        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString






        share|improve this answer































          2














          number = 123456.7089;
          result = parseInt( number ).toLocaleString() + "<br>";
          result = number.toLocaleString( 'pt-BR' ) + "<br>";

          var el = document.getElementById( 'result' );
          el.innerHTML = result;


          <div id="result"></div>





          share|improve this answer





















          • 6





            Can you please add some description as well so that op and other people can understand that how this code actually solve the problem. Thanks

            – Punit Gajjar
            Sep 26 '17 at 13:58



















          1














          PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.






          share|improve this answer
























          • The first link follows to JS implementation of PHP's version. It's useful.

            – o_nix
            Apr 8 '14 at 15:11



















          1














          All you need to do is just really this:



          123000.9123.toLocaleString()
          //result will be "123,000.912"





          share|improve this answer
























          • Unfortunately it depends on your platform. Some have a toLocaleString() which does not add the commas, or lacks other features in the standard. It's easy to check for toLocaleString presence but not to check for its compliance.

            – hippietrail
            Oct 3 '17 at 0:56



















          -1














          I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.



          function getFormattedCurrency(num) {
          num = num.toFixed(2)
          var cents = (num - Math.floor(num)).toFixed(2);
          return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3753483%2fjavascript-thousand-separator-string-format%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            12 Answers
            12






            active

            oldest

            votes








            12 Answers
            12






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            100














            Update (7 years later)



            The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString



            So you can do:



            (1234567.89).toLocaleString('en')              // for numeric input
            parseFloat("1234567.89").toLocaleString('en') // for string input


            The function implemented below works, too, but simply isn't necessary.



            (I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)





            Original Answer



            According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:



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


            Edit:
            To go the other way (convert string with commas to number), you could do something like this:



            parseFloat("1,234,567.89".replace(/,/g,''))





            share|improve this answer


























            • Really Really Appreciate It // But How Can i Convert that string (with commas) to a number ?

              – LostLord
              Sep 20 '10 at 16:51











            • this function breaks for numbers greater than 100,000

              – DevZer0
              Apr 28 '15 at 7:27






            • 1





              @DevZer0 no it doesn't

              – Tallboy
              Jan 6 '16 at 2:27











            • I needed "the other" way. works perfectly. Thanks!

              – Erik Kalkoken
              Feb 3 '16 at 15:07











            • Kind of a clumsy solution, but works.

              – Kirill E.
              May 13 '16 at 15:49


















            100














            Update (7 years later)



            The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString



            So you can do:



            (1234567.89).toLocaleString('en')              // for numeric input
            parseFloat("1234567.89").toLocaleString('en') // for string input


            The function implemented below works, too, but simply isn't necessary.



            (I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)





            Original Answer



            According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:



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


            Edit:
            To go the other way (convert string with commas to number), you could do something like this:



            parseFloat("1,234,567.89".replace(/,/g,''))





            share|improve this answer


























            • Really Really Appreciate It // But How Can i Convert that string (with commas) to a number ?

              – LostLord
              Sep 20 '10 at 16:51











            • this function breaks for numbers greater than 100,000

              – DevZer0
              Apr 28 '15 at 7:27






            • 1





              @DevZer0 no it doesn't

              – Tallboy
              Jan 6 '16 at 2:27











            • I needed "the other" way. works perfectly. Thanks!

              – Erik Kalkoken
              Feb 3 '16 at 15:07











            • Kind of a clumsy solution, but works.

              – Kirill E.
              May 13 '16 at 15:49
















            100












            100








            100







            Update (7 years later)



            The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString



            So you can do:



            (1234567.89).toLocaleString('en')              // for numeric input
            parseFloat("1234567.89").toLocaleString('en') // for string input


            The function implemented below works, too, but simply isn't necessary.



            (I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)





            Original Answer



            According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:



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


            Edit:
            To go the other way (convert string with commas to number), you could do something like this:



            parseFloat("1,234,567.89".replace(/,/g,''))





            share|improve this answer















            Update (7 years later)



            The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString



            So you can do:



            (1234567.89).toLocaleString('en')              // for numeric input
            parseFloat("1234567.89").toLocaleString('en') // for string input


            The function implemented below works, too, but simply isn't necessary.



            (I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)





            Original Answer



            According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:



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


            Edit:
            To go the other way (convert string with commas to number), you could do something like this:



            parseFloat("1,234,567.89".replace(/,/g,''))






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 4 '17 at 15:00









            RiZKiT

            712614




            712614










            answered Sep 20 '10 at 16:38









            Tim GoodmanTim Goodman

            15.6k54972




            15.6k54972













            • Really Really Appreciate It // But How Can i Convert that string (with commas) to a number ?

              – LostLord
              Sep 20 '10 at 16:51











            • this function breaks for numbers greater than 100,000

              – DevZer0
              Apr 28 '15 at 7:27






            • 1





              @DevZer0 no it doesn't

              – Tallboy
              Jan 6 '16 at 2:27











            • I needed "the other" way. works perfectly. Thanks!

              – Erik Kalkoken
              Feb 3 '16 at 15:07











            • Kind of a clumsy solution, but works.

              – Kirill E.
              May 13 '16 at 15:49





















            • Really Really Appreciate It // But How Can i Convert that string (with commas) to a number ?

              – LostLord
              Sep 20 '10 at 16:51











            • this function breaks for numbers greater than 100,000

              – DevZer0
              Apr 28 '15 at 7:27






            • 1





              @DevZer0 no it doesn't

              – Tallboy
              Jan 6 '16 at 2:27











            • I needed "the other" way. works perfectly. Thanks!

              – Erik Kalkoken
              Feb 3 '16 at 15:07











            • Kind of a clumsy solution, but works.

              – Kirill E.
              May 13 '16 at 15:49



















            Really Really Appreciate It // But How Can i Convert that string (with commas) to a number ?

            – LostLord
            Sep 20 '10 at 16:51





            Really Really Appreciate It // But How Can i Convert that string (with commas) to a number ?

            – LostLord
            Sep 20 '10 at 16:51













            this function breaks for numbers greater than 100,000

            – DevZer0
            Apr 28 '15 at 7:27





            this function breaks for numbers greater than 100,000

            – DevZer0
            Apr 28 '15 at 7:27




            1




            1





            @DevZer0 no it doesn't

            – Tallboy
            Jan 6 '16 at 2:27





            @DevZer0 no it doesn't

            – Tallboy
            Jan 6 '16 at 2:27













            I needed "the other" way. works perfectly. Thanks!

            – Erik Kalkoken
            Feb 3 '16 at 15:07





            I needed "the other" way. works perfectly. Thanks!

            – Erik Kalkoken
            Feb 3 '16 at 15:07













            Kind of a clumsy solution, but works.

            – Kirill E.
            May 13 '16 at 15:49







            Kind of a clumsy solution, but works.

            – Kirill E.
            May 13 '16 at 15:49















            119














            If is about localizing thousands separators, delimiters and decimal separators, go with the following:



            // --> numObj.toLocaleString( [locales [, options] ] )
            parseInt( number ).toLocaleString();


            There are several options you can use (and even locales with fallbacks):






            number = 123456.7089;

            result = parseInt( number ).toLocaleString() + "<br>";
            result += number.toLocaleString( 'de-DE' ) + "<br>";
            result += number.toLocaleString( 'ar-EG' ) + "<br>";
            result += number.toLocaleString( 'ja-JP', {
            style : 'currency',
            currency : 'JPY',
            currencyDisplay : 'symbol',
            useGrouping : true
            } ) + "<br>";
            result += number.toLocaleString( [ 'jav', 'en' ], {
            localeMatcher : 'lookup',
            style : 'decimal',
            minimumIntegerDigits : 2,
            minimumFractionDigits : 2,
            maximumFractionDigits : 3,
            minimumSignificantDigits : 2,
            maximumSignificantDigits : 3
            } ) + "<br>";

            var el = document.getElementById( 'result' );
            el.innerHTML = result;

            <div id="result"></div>





            Details on the MDN info page.



            Edit: Commentor @I like Serena adds the following:




            To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.







            share|improve this answer





















            • 3





              All I can say is wow. Beautiful.

              – pimbrouwers
              Mar 3 '14 at 20:59






            • 12





              +1 for not reinventing the wheel.

              – Mariano Cavallo
              Mar 20 '14 at 14:18






            • 4





              assuming the browser's locale is always what you want...

              – sibidiba
              Apr 15 '14 at 11:09






            • 1





              You're my hero, kaiser.

              – Michael
              Feb 17 '15 at 16:07






            • 2





              To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

              – I like Serena
              Sep 12 '15 at 21:54


















            119














            If is about localizing thousands separators, delimiters and decimal separators, go with the following:



            // --> numObj.toLocaleString( [locales [, options] ] )
            parseInt( number ).toLocaleString();


            There are several options you can use (and even locales with fallbacks):






            number = 123456.7089;

            result = parseInt( number ).toLocaleString() + "<br>";
            result += number.toLocaleString( 'de-DE' ) + "<br>";
            result += number.toLocaleString( 'ar-EG' ) + "<br>";
            result += number.toLocaleString( 'ja-JP', {
            style : 'currency',
            currency : 'JPY',
            currencyDisplay : 'symbol',
            useGrouping : true
            } ) + "<br>";
            result += number.toLocaleString( [ 'jav', 'en' ], {
            localeMatcher : 'lookup',
            style : 'decimal',
            minimumIntegerDigits : 2,
            minimumFractionDigits : 2,
            maximumFractionDigits : 3,
            minimumSignificantDigits : 2,
            maximumSignificantDigits : 3
            } ) + "<br>";

            var el = document.getElementById( 'result' );
            el.innerHTML = result;

            <div id="result"></div>





            Details on the MDN info page.



            Edit: Commentor @I like Serena adds the following:




            To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.







            share|improve this answer





















            • 3





              All I can say is wow. Beautiful.

              – pimbrouwers
              Mar 3 '14 at 20:59






            • 12





              +1 for not reinventing the wheel.

              – Mariano Cavallo
              Mar 20 '14 at 14:18






            • 4





              assuming the browser's locale is always what you want...

              – sibidiba
              Apr 15 '14 at 11:09






            • 1





              You're my hero, kaiser.

              – Michael
              Feb 17 '15 at 16:07






            • 2





              To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

              – I like Serena
              Sep 12 '15 at 21:54
















            119












            119








            119







            If is about localizing thousands separators, delimiters and decimal separators, go with the following:



            // --> numObj.toLocaleString( [locales [, options] ] )
            parseInt( number ).toLocaleString();


            There are several options you can use (and even locales with fallbacks):






            number = 123456.7089;

            result = parseInt( number ).toLocaleString() + "<br>";
            result += number.toLocaleString( 'de-DE' ) + "<br>";
            result += number.toLocaleString( 'ar-EG' ) + "<br>";
            result += number.toLocaleString( 'ja-JP', {
            style : 'currency',
            currency : 'JPY',
            currencyDisplay : 'symbol',
            useGrouping : true
            } ) + "<br>";
            result += number.toLocaleString( [ 'jav', 'en' ], {
            localeMatcher : 'lookup',
            style : 'decimal',
            minimumIntegerDigits : 2,
            minimumFractionDigits : 2,
            maximumFractionDigits : 3,
            minimumSignificantDigits : 2,
            maximumSignificantDigits : 3
            } ) + "<br>";

            var el = document.getElementById( 'result' );
            el.innerHTML = result;

            <div id="result"></div>





            Details on the MDN info page.



            Edit: Commentor @I like Serena adds the following:




            To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.







            share|improve this answer















            If is about localizing thousands separators, delimiters and decimal separators, go with the following:



            // --> numObj.toLocaleString( [locales [, options] ] )
            parseInt( number ).toLocaleString();


            There are several options you can use (and even locales with fallbacks):






            number = 123456.7089;

            result = parseInt( number ).toLocaleString() + "<br>";
            result += number.toLocaleString( 'de-DE' ) + "<br>";
            result += number.toLocaleString( 'ar-EG' ) + "<br>";
            result += number.toLocaleString( 'ja-JP', {
            style : 'currency',
            currency : 'JPY',
            currencyDisplay : 'symbol',
            useGrouping : true
            } ) + "<br>";
            result += number.toLocaleString( [ 'jav', 'en' ], {
            localeMatcher : 'lookup',
            style : 'decimal',
            minimumIntegerDigits : 2,
            minimumFractionDigits : 2,
            maximumFractionDigits : 3,
            minimumSignificantDigits : 2,
            maximumSignificantDigits : 3
            } ) + "<br>";

            var el = document.getElementById( 'result' );
            el.innerHTML = result;

            <div id="result"></div>





            Details on the MDN info page.



            Edit: Commentor @I like Serena adds the following:




            To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.







            number = 123456.7089;

            result = parseInt( number ).toLocaleString() + "<br>";
            result += number.toLocaleString( 'de-DE' ) + "<br>";
            result += number.toLocaleString( 'ar-EG' ) + "<br>";
            result += number.toLocaleString( 'ja-JP', {
            style : 'currency',
            currency : 'JPY',
            currencyDisplay : 'symbol',
            useGrouping : true
            } ) + "<br>";
            result += number.toLocaleString( [ 'jav', 'en' ], {
            localeMatcher : 'lookup',
            style : 'decimal',
            minimumIntegerDigits : 2,
            minimumFractionDigits : 2,
            maximumFractionDigits : 3,
            minimumSignificantDigits : 2,
            maximumSignificantDigits : 3
            } ) + "<br>";

            var el = document.getElementById( 'result' );
            el.innerHTML = result;

            <div id="result"></div>





            number = 123456.7089;

            result = parseInt( number ).toLocaleString() + "<br>";
            result += number.toLocaleString( 'de-DE' ) + "<br>";
            result += number.toLocaleString( 'ar-EG' ) + "<br>";
            result += number.toLocaleString( 'ja-JP', {
            style : 'currency',
            currency : 'JPY',
            currencyDisplay : 'symbol',
            useGrouping : true
            } ) + "<br>";
            result += number.toLocaleString( [ 'jav', 'en' ], {
            localeMatcher : 'lookup',
            style : 'decimal',
            minimumIntegerDigits : 2,
            minimumFractionDigits : 2,
            maximumFractionDigits : 3,
            minimumSignificantDigits : 2,
            maximumSignificantDigits : 3
            } ) + "<br>";

            var el = document.getElementById( 'result' );
            el.innerHTML = result;

            <div id="result"></div>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 23 '17 at 12:10









            Community

            11




            11










            answered Nov 7 '13 at 16:10









            kaiserkaiser

            14.8k157392




            14.8k157392








            • 3





              All I can say is wow. Beautiful.

              – pimbrouwers
              Mar 3 '14 at 20:59






            • 12





              +1 for not reinventing the wheel.

              – Mariano Cavallo
              Mar 20 '14 at 14:18






            • 4





              assuming the browser's locale is always what you want...

              – sibidiba
              Apr 15 '14 at 11:09






            • 1





              You're my hero, kaiser.

              – Michael
              Feb 17 '15 at 16:07






            • 2





              To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

              – I like Serena
              Sep 12 '15 at 21:54
















            • 3





              All I can say is wow. Beautiful.

              – pimbrouwers
              Mar 3 '14 at 20:59






            • 12





              +1 for not reinventing the wheel.

              – Mariano Cavallo
              Mar 20 '14 at 14:18






            • 4





              assuming the browser's locale is always what you want...

              – sibidiba
              Apr 15 '14 at 11:09






            • 1





              You're my hero, kaiser.

              – Michael
              Feb 17 '15 at 16:07






            • 2





              To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

              – I like Serena
              Sep 12 '15 at 21:54










            3




            3





            All I can say is wow. Beautiful.

            – pimbrouwers
            Mar 3 '14 at 20:59





            All I can say is wow. Beautiful.

            – pimbrouwers
            Mar 3 '14 at 20:59




            12




            12





            +1 for not reinventing the wheel.

            – Mariano Cavallo
            Mar 20 '14 at 14:18





            +1 for not reinventing the wheel.

            – Mariano Cavallo
            Mar 20 '14 at 14:18




            4




            4





            assuming the browser's locale is always what you want...

            – sibidiba
            Apr 15 '14 at 11:09





            assuming the browser's locale is always what you want...

            – sibidiba
            Apr 15 '14 at 11:09




            1




            1





            You're my hero, kaiser.

            – Michael
            Feb 17 '15 at 16:07





            You're my hero, kaiser.

            – Michael
            Feb 17 '15 at 16:07




            2




            2





            To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

            – I like Serena
            Sep 12 '15 at 21:54







            To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

            – I like Serena
            Sep 12 '15 at 21:54













            26














            Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.






            const format = num => {
            const n = String(num),
            p = n.indexOf('.')
            return n.replace(
            /d(?=(?:d{3})+(?:.|$))/g,
            (m, i) => p < 0 || i < p ? `${m},` : m
            )
            }

            [
            format(100), // "100"
            format(1000), // "1,000"
            format(1e10), // "10,000,000,000"
            format(1000.001001) // "1,000.001001"
            ]
            .forEach(n => console.log(n))





            » Verbose regex explanation (regex101.com)



            flow diagram






            share|improve this answer


























            • Has this syntax diagram been created on regex101.com?

              – Gerold Broser
              Apr 19 '17 at 23:26






            • 1





              @GeroldBroser regexper.com

              – Emissary
              Apr 20 '17 at 5:46
















            26














            Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.






            const format = num => {
            const n = String(num),
            p = n.indexOf('.')
            return n.replace(
            /d(?=(?:d{3})+(?:.|$))/g,
            (m, i) => p < 0 || i < p ? `${m},` : m
            )
            }

            [
            format(100), // "100"
            format(1000), // "1,000"
            format(1e10), // "10,000,000,000"
            format(1000.001001) // "1,000.001001"
            ]
            .forEach(n => console.log(n))





            » Verbose regex explanation (regex101.com)



            flow diagram






            share|improve this answer


























            • Has this syntax diagram been created on regex101.com?

              – Gerold Broser
              Apr 19 '17 at 23:26






            • 1





              @GeroldBroser regexper.com

              – Emissary
              Apr 20 '17 at 5:46














            26












            26








            26







            Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.






            const format = num => {
            const n = String(num),
            p = n.indexOf('.')
            return n.replace(
            /d(?=(?:d{3})+(?:.|$))/g,
            (m, i) => p < 0 || i < p ? `${m},` : m
            )
            }

            [
            format(100), // "100"
            format(1000), // "1,000"
            format(1e10), // "10,000,000,000"
            format(1000.001001) // "1,000.001001"
            ]
            .forEach(n => console.log(n))





            » Verbose regex explanation (regex101.com)



            flow diagram






            share|improve this answer















            Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.






            const format = num => {
            const n = String(num),
            p = n.indexOf('.')
            return n.replace(
            /d(?=(?:d{3})+(?:.|$))/g,
            (m, i) => p < 0 || i < p ? `${m},` : m
            )
            }

            [
            format(100), // "100"
            format(1000), // "1,000"
            format(1e10), // "10,000,000,000"
            format(1000.001001) // "1,000.001001"
            ]
            .forEach(n => console.log(n))





            » Verbose regex explanation (regex101.com)



            flow diagram






            const format = num => {
            const n = String(num),
            p = n.indexOf('.')
            return n.replace(
            /d(?=(?:d{3})+(?:.|$))/g,
            (m, i) => p < 0 || i < p ? `${m},` : m
            )
            }

            [
            format(100), // "100"
            format(1000), // "1,000"
            format(1e10), // "10,000,000,000"
            format(1000.001001) // "1,000.001001"
            ]
            .forEach(n => console.log(n))





            const format = num => {
            const n = String(num),
            p = n.indexOf('.')
            return n.replace(
            /d(?=(?:d{3})+(?:.|$))/g,
            (m, i) => p < 0 || i < p ? `${m},` : m
            )
            }

            [
            format(100), // "100"
            format(1000), // "1,000"
            format(1e10), // "10,000,000,000"
            format(1000.001001) // "1,000.001001"
            ]
            .forEach(n => console.log(n))






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 15 '18 at 7:38

























            answered Aug 15 '14 at 11:32









            EmissaryEmissary

            7,46884254




            7,46884254













            • Has this syntax diagram been created on regex101.com?

              – Gerold Broser
              Apr 19 '17 at 23:26






            • 1





              @GeroldBroser regexper.com

              – Emissary
              Apr 20 '17 at 5:46



















            • Has this syntax diagram been created on regex101.com?

              – Gerold Broser
              Apr 19 '17 at 23:26






            • 1





              @GeroldBroser regexper.com

              – Emissary
              Apr 20 '17 at 5:46

















            Has this syntax diagram been created on regex101.com?

            – Gerold Broser
            Apr 19 '17 at 23:26





            Has this syntax diagram been created on regex101.com?

            – Gerold Broser
            Apr 19 '17 at 23:26




            1




            1





            @GeroldBroser regexper.com

            – Emissary
            Apr 20 '17 at 5:46





            @GeroldBroser regexper.com

            – Emissary
            Apr 20 '17 at 5:46











            8














            There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number



            It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:



            $.number(12345.4556, 2);          // -> 12,345.46
            $.number(12345.4556, 3, ',', ' ') // -> 12 345,456


            You can use it inside input fields directly, which is nicer, using same options like above:



            $("input").number(true, 2);


            Or you can apply to a whole set of DOM elements using selector:



            $('span.number').number(true, 2);





            share|improve this answer




























              8














              There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number



              It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:



              $.number(12345.4556, 2);          // -> 12,345.46
              $.number(12345.4556, 3, ',', ' ') // -> 12 345,456


              You can use it inside input fields directly, which is nicer, using same options like above:



              $("input").number(true, 2);


              Or you can apply to a whole set of DOM elements using selector:



              $('span.number').number(true, 2);





              share|improve this answer


























                8












                8








                8







                There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number



                It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:



                $.number(12345.4556, 2);          // -> 12,345.46
                $.number(12345.4556, 3, ',', ' ') // -> 12 345,456


                You can use it inside input fields directly, which is nicer, using same options like above:



                $("input").number(true, 2);


                Or you can apply to a whole set of DOM elements using selector:



                $('span.number').number(true, 2);





                share|improve this answer













                There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number



                It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:



                $.number(12345.4556, 2);          // -> 12,345.46
                $.number(12345.4556, 3, ',', ' ') // -> 12 345,456


                You can use it inside input fields directly, which is nicer, using same options like above:



                $("input").number(true, 2);


                Or you can apply to a whole set of DOM elements using selector:



                $('span.number').number(true, 2);






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 1 '14 at 14:51









                qdevqdev

                874915




                874915























                    4














                    // thousand separates a digit-only string using commas
                    // by element: onkeyup = "ThousandSeparate(this)"
                    // by ID: onkeyup = "ThousandSeparate('txt1','lbl1')"
                    function ThousandSeparate()
                    {
                    if (arguments.length == 1)
                    {
                    var V = arguments[0].value;
                    V = V.replace(/,/g,'');
                    var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                    while(R.test(V))
                    {
                    V = V.replace(R, '$1,$2');
                    }
                    arguments[0].value = V;
                    }
                    else if ( arguments.length == 2)
                    {
                    var V = document.getElementById(arguments[0]).value;
                    var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                    while(R.test(V))
                    {
                    V = V.replace(R, '$1,$2');
                    }
                    document.getElementById(arguments[1]).innerHTML = V;
                    }
                    else return false;
                    }





                    share|improve this answer






























                      4














                      // thousand separates a digit-only string using commas
                      // by element: onkeyup = "ThousandSeparate(this)"
                      // by ID: onkeyup = "ThousandSeparate('txt1','lbl1')"
                      function ThousandSeparate()
                      {
                      if (arguments.length == 1)
                      {
                      var V = arguments[0].value;
                      V = V.replace(/,/g,'');
                      var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                      while(R.test(V))
                      {
                      V = V.replace(R, '$1,$2');
                      }
                      arguments[0].value = V;
                      }
                      else if ( arguments.length == 2)
                      {
                      var V = document.getElementById(arguments[0]).value;
                      var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                      while(R.test(V))
                      {
                      V = V.replace(R, '$1,$2');
                      }
                      document.getElementById(arguments[1]).innerHTML = V;
                      }
                      else return false;
                      }





                      share|improve this answer




























                        4












                        4








                        4







                        // thousand separates a digit-only string using commas
                        // by element: onkeyup = "ThousandSeparate(this)"
                        // by ID: onkeyup = "ThousandSeparate('txt1','lbl1')"
                        function ThousandSeparate()
                        {
                        if (arguments.length == 1)
                        {
                        var V = arguments[0].value;
                        V = V.replace(/,/g,'');
                        var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                        while(R.test(V))
                        {
                        V = V.replace(R, '$1,$2');
                        }
                        arguments[0].value = V;
                        }
                        else if ( arguments.length == 2)
                        {
                        var V = document.getElementById(arguments[0]).value;
                        var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                        while(R.test(V))
                        {
                        V = V.replace(R, '$1,$2');
                        }
                        document.getElementById(arguments[1]).innerHTML = V;
                        }
                        else return false;
                        }





                        share|improve this answer















                        // thousand separates a digit-only string using commas
                        // by element: onkeyup = "ThousandSeparate(this)"
                        // by ID: onkeyup = "ThousandSeparate('txt1','lbl1')"
                        function ThousandSeparate()
                        {
                        if (arguments.length == 1)
                        {
                        var V = arguments[0].value;
                        V = V.replace(/,/g,'');
                        var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                        while(R.test(V))
                        {
                        V = V.replace(R, '$1,$2');
                        }
                        arguments[0].value = V;
                        }
                        else if ( arguments.length == 2)
                        {
                        var V = document.getElementById(arguments[0]).value;
                        var R = new RegExp('(-?[0-9]+)([0-9]{3})');
                        while(R.test(V))
                        {
                        V = V.replace(R, '$1,$2');
                        }
                        document.getElementById(arguments[1]).innerHTML = V;
                        }
                        else return false;
                        }






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jul 14 '11 at 19:22









                        Chris Frederick

                        4,37832738




                        4,37832738










                        answered Jul 14 '11 at 10:21









                        h.foroutanh.foroutan

                        412




                        412























                            3














                            I use this:



                            function numberWithCommas(number) {
                            return number.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
                            }


                            source: link






                            share|improve this answer
























                            • '123452343267.0505'.replace(/B(?=(d{3})+(?!d))/g, ","); "123,452,343,267.0,505" - notice that last comma after the decimal point.

                              – hippietrail
                              Oct 3 '17 at 0:53


















                            3














                            I use this:



                            function numberWithCommas(number) {
                            return number.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
                            }


                            source: link






                            share|improve this answer
























                            • '123452343267.0505'.replace(/B(?=(d{3})+(?!d))/g, ","); "123,452,343,267.0,505" - notice that last comma after the decimal point.

                              – hippietrail
                              Oct 3 '17 at 0:53
















                            3












                            3








                            3







                            I use this:



                            function numberWithCommas(number) {
                            return number.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
                            }


                            source: link






                            share|improve this answer













                            I use this:



                            function numberWithCommas(number) {
                            return number.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
                            }


                            source: link







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jun 26 '17 at 18:24









                            Abhishek GoelAbhishek Goel

                            10.6k66857




                            10.6k66857













                            • '123452343267.0505'.replace(/B(?=(d{3})+(?!d))/g, ","); "123,452,343,267.0,505" - notice that last comma after the decimal point.

                              – hippietrail
                              Oct 3 '17 at 0:53





















                            • '123452343267.0505'.replace(/B(?=(d{3})+(?!d))/g, ","); "123,452,343,267.0,505" - notice that last comma after the decimal point.

                              – hippietrail
                              Oct 3 '17 at 0:53



















                            '123452343267.0505'.replace(/B(?=(d{3})+(?!d))/g, ","); "123,452,343,267.0,505" - notice that last comma after the decimal point.

                            – hippietrail
                            Oct 3 '17 at 0:53







                            '123452343267.0505'.replace(/B(?=(d{3})+(?!d))/g, ","); "123,452,343,267.0,505" - notice that last comma after the decimal point.

                            – hippietrail
                            Oct 3 '17 at 0:53













                            3














                            You can use javascript. below are the code, it will only accept numeric and one dot




                            here is the javascript




                            <script >

                            function FormatCurrency(ctrl) {
                            //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                            if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                            return;
                            }

                            var val = ctrl.value;

                            val = val.replace(/,/g, "")
                            ctrl.value = "";
                            val += '';
                            x = val.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');
                            }

                            ctrl.value = x1 + x2;
                            }

                            function CheckNumeric() {
                            return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
                            }

                            </script>



                            HTML




                            <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />


                            DEMO JSFIDDLE






                            share|improve this answer




























                              3














                              You can use javascript. below are the code, it will only accept numeric and one dot




                              here is the javascript




                              <script >

                              function FormatCurrency(ctrl) {
                              //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                              if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                              return;
                              }

                              var val = ctrl.value;

                              val = val.replace(/,/g, "")
                              ctrl.value = "";
                              val += '';
                              x = val.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');
                              }

                              ctrl.value = x1 + x2;
                              }

                              function CheckNumeric() {
                              return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
                              }

                              </script>



                              HTML




                              <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />


                              DEMO JSFIDDLE






                              share|improve this answer


























                                3












                                3








                                3







                                You can use javascript. below are the code, it will only accept numeric and one dot




                                here is the javascript




                                <script >

                                function FormatCurrency(ctrl) {
                                //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                                if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                                return;
                                }

                                var val = ctrl.value;

                                val = val.replace(/,/g, "")
                                ctrl.value = "";
                                val += '';
                                x = val.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');
                                }

                                ctrl.value = x1 + x2;
                                }

                                function CheckNumeric() {
                                return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
                                }

                                </script>



                                HTML




                                <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />


                                DEMO JSFIDDLE






                                share|improve this answer













                                You can use javascript. below are the code, it will only accept numeric and one dot




                                here is the javascript




                                <script >

                                function FormatCurrency(ctrl) {
                                //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                                if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                                return;
                                }

                                var val = ctrl.value;

                                val = val.replace(/,/g, "")
                                ctrl.value = "";
                                val += '';
                                x = val.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');
                                }

                                ctrl.value = x1 + x2;
                                }

                                function CheckNumeric() {
                                return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
                                }

                                </script>



                                HTML




                                <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />


                                DEMO JSFIDDLE







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Aug 18 '17 at 7:13









                                AwtszsAwtszs

                                2051733




                                2051733























                                    3














                                    var number = 35002343;

                                    console.log(number.toLocaleString());


                                    for the reference you can check here
                                    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString






                                    share|improve this answer




























                                      3














                                      var number = 35002343;

                                      console.log(number.toLocaleString());


                                      for the reference you can check here
                                      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString






                                      share|improve this answer


























                                        3












                                        3








                                        3







                                        var number = 35002343;

                                        console.log(number.toLocaleString());


                                        for the reference you can check here
                                        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString






                                        share|improve this answer













                                        var number = 35002343;

                                        console.log(number.toLocaleString());


                                        for the reference you can check here
                                        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Feb 6 '18 at 12:52









                                        vikashraj144vikashraj144

                                        516




                                        516























                                            2














                                            number = 123456.7089;
                                            result = parseInt( number ).toLocaleString() + "<br>";
                                            result = number.toLocaleString( 'pt-BR' ) + "<br>";

                                            var el = document.getElementById( 'result' );
                                            el.innerHTML = result;


                                            <div id="result"></div>





                                            share|improve this answer





















                                            • 6





                                              Can you please add some description as well so that op and other people can understand that how this code actually solve the problem. Thanks

                                              – Punit Gajjar
                                              Sep 26 '17 at 13:58
















                                            2














                                            number = 123456.7089;
                                            result = parseInt( number ).toLocaleString() + "<br>";
                                            result = number.toLocaleString( 'pt-BR' ) + "<br>";

                                            var el = document.getElementById( 'result' );
                                            el.innerHTML = result;


                                            <div id="result"></div>





                                            share|improve this answer





















                                            • 6





                                              Can you please add some description as well so that op and other people can understand that how this code actually solve the problem. Thanks

                                              – Punit Gajjar
                                              Sep 26 '17 at 13:58














                                            2












                                            2








                                            2







                                            number = 123456.7089;
                                            result = parseInt( number ).toLocaleString() + "<br>";
                                            result = number.toLocaleString( 'pt-BR' ) + "<br>";

                                            var el = document.getElementById( 'result' );
                                            el.innerHTML = result;


                                            <div id="result"></div>





                                            share|improve this answer















                                            number = 123456.7089;
                                            result = parseInt( number ).toLocaleString() + "<br>";
                                            result = number.toLocaleString( 'pt-BR' ) + "<br>";

                                            var el = document.getElementById( 'result' );
                                            el.innerHTML = result;


                                            <div id="result"></div>






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Sep 26 '17 at 15:38









                                            Rory McCrossan

                                            246k29213252




                                            246k29213252










                                            answered Sep 26 '17 at 13:35









                                            RicardoRicardo

                                            211




                                            211








                                            • 6





                                              Can you please add some description as well so that op and other people can understand that how this code actually solve the problem. Thanks

                                              – Punit Gajjar
                                              Sep 26 '17 at 13:58














                                            • 6





                                              Can you please add some description as well so that op and other people can understand that how this code actually solve the problem. Thanks

                                              – Punit Gajjar
                                              Sep 26 '17 at 13:58








                                            6




                                            6





                                            Can you please add some description as well so that op and other people can understand that how this code actually solve the problem. Thanks

                                            – Punit Gajjar
                                            Sep 26 '17 at 13:58





                                            Can you please add some description as well so that op and other people can understand that how this code actually solve the problem. Thanks

                                            – Punit Gajjar
                                            Sep 26 '17 at 13:58











                                            1














                                            PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.






                                            share|improve this answer
























                                            • The first link follows to JS implementation of PHP's version. It's useful.

                                              – o_nix
                                              Apr 8 '14 at 15:11
















                                            1














                                            PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.






                                            share|improve this answer
























                                            • The first link follows to JS implementation of PHP's version. It's useful.

                                              – o_nix
                                              Apr 8 '14 at 15:11














                                            1












                                            1








                                            1







                                            PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.






                                            share|improve this answer













                                            PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Apr 12 '11 at 11:13









                                            istvanpistvanp

                                            2,35931824




                                            2,35931824













                                            • The first link follows to JS implementation of PHP's version. It's useful.

                                              – o_nix
                                              Apr 8 '14 at 15:11



















                                            • The first link follows to JS implementation of PHP's version. It's useful.

                                              – o_nix
                                              Apr 8 '14 at 15:11

















                                            The first link follows to JS implementation of PHP's version. It's useful.

                                            – o_nix
                                            Apr 8 '14 at 15:11





                                            The first link follows to JS implementation of PHP's version. It's useful.

                                            – o_nix
                                            Apr 8 '14 at 15:11











                                            1














                                            All you need to do is just really this:



                                            123000.9123.toLocaleString()
                                            //result will be "123,000.912"





                                            share|improve this answer
























                                            • Unfortunately it depends on your platform. Some have a toLocaleString() which does not add the commas, or lacks other features in the standard. It's easy to check for toLocaleString presence but not to check for its compliance.

                                              – hippietrail
                                              Oct 3 '17 at 0:56
















                                            1














                                            All you need to do is just really this:



                                            123000.9123.toLocaleString()
                                            //result will be "123,000.912"





                                            share|improve this answer
























                                            • Unfortunately it depends on your platform. Some have a toLocaleString() which does not add the commas, or lacks other features in the standard. It's easy to check for toLocaleString presence but not to check for its compliance.

                                              – hippietrail
                                              Oct 3 '17 at 0:56














                                            1












                                            1








                                            1







                                            All you need to do is just really this:



                                            123000.9123.toLocaleString()
                                            //result will be "123,000.912"





                                            share|improve this answer













                                            All you need to do is just really this:



                                            123000.9123.toLocaleString()
                                            //result will be "123,000.912"






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Jul 10 '17 at 2:24









                                            EzeeweiEzeewei

                                            2,40932664




                                            2,40932664













                                            • Unfortunately it depends on your platform. Some have a toLocaleString() which does not add the commas, or lacks other features in the standard. It's easy to check for toLocaleString presence but not to check for its compliance.

                                              – hippietrail
                                              Oct 3 '17 at 0:56



















                                            • Unfortunately it depends on your platform. Some have a toLocaleString() which does not add the commas, or lacks other features in the standard. It's easy to check for toLocaleString presence but not to check for its compliance.

                                              – hippietrail
                                              Oct 3 '17 at 0:56

















                                            Unfortunately it depends on your platform. Some have a toLocaleString() which does not add the commas, or lacks other features in the standard. It's easy to check for toLocaleString presence but not to check for its compliance.

                                            – hippietrail
                                            Oct 3 '17 at 0:56





                                            Unfortunately it depends on your platform. Some have a toLocaleString() which does not add the commas, or lacks other features in the standard. It's easy to check for toLocaleString presence but not to check for its compliance.

                                            – hippietrail
                                            Oct 3 '17 at 0:56











                                            -1














                                            I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.



                                            function getFormattedCurrency(num) {
                                            num = num.toFixed(2)
                                            var cents = (num - Math.floor(num)).toFixed(2);
                                            return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
                                            }





                                            share|improve this answer




























                                              -1














                                              I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.



                                              function getFormattedCurrency(num) {
                                              num = num.toFixed(2)
                                              var cents = (num - Math.floor(num)).toFixed(2);
                                              return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
                                              }





                                              share|improve this answer


























                                                -1












                                                -1








                                                -1







                                                I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.



                                                function getFormattedCurrency(num) {
                                                num = num.toFixed(2)
                                                var cents = (num - Math.floor(num)).toFixed(2);
                                                return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
                                                }





                                                share|improve this answer













                                                I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.



                                                function getFormattedCurrency(num) {
                                                num = num.toFixed(2)
                                                var cents = (num - Math.floor(num)).toFixed(2);
                                                return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 19 '15 at 16:07









                                                Spencer SullivanSpencer Sullivan

                                                18512




                                                18512






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3753483%2fjavascript-thousand-separator-string-format%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    MongoDB - Not Authorized To Execute Command

                                                    How to fix TextFormField cause rebuild widget in Flutter

                                                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith