0

I try to convert the number in text box as comma separated values while typing but only the last values are taken.

<script type="text/javascript">

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


</script>

This is the HTML file:

<asp:TextBox ID="txtbudamt" runat="server" CssClass="text_box" Height="22px" Width="140px" onkeyup="this.value=addCommas(this.value);"    onkeydown="return (event.keyCode!=13);" AutoComplete="Off" TabIndex="7"></asp:TextBox>
  • When I enter numbers till 9999 it gives correct output like 9,999
  • When I go for 10000 it gives 1,0,000
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
dr.engg
  • 27
  • 1
  • 9
  • 1
    The more appropriate way to add comma would be to parse number as `int` and format the value using your culture. – Sinatr Sep 28 '20 at 09:52
  • 1
    Does this answer your question? [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Ivar Sep 28 '20 at 09:54
  • i cant do that because i have to perform some math function also the external api will take only int or double , and more over i just what the comma separator in the html page alone – dr.engg Sep 28 '20 at 09:54
  • @ivar i did check with the link you have attached but , none of them are working for exception this jquery and with this mistake – dr.engg Sep 28 '20 at 09:59
  • 2
    @dr.engg You checked all 53 answers already? Simply use `return parseFloat(nStr).toLocaleString();`. (Also, there is no jQuery what so ever in the code you provided.) – Ivar Sep 28 '20 at 09:59

1 Answers1

0

You can simply use toLocaleString for this. It is also supported on most browsers.

function addCommas(nStr) {
   return parseFloat(nStr).toLocaleString('en-GB');
}
AKT
  • 942
  • 6
  • 16
  • this method is not allowing me to go beyond 9999 like if i type 10000 it auto changes to 1 and becomes NaN – dr.engg Sep 28 '20 at 10:31