Search code examples
javascriptasp.netstring-formattingseparatoronkeyup

Thousands separator using Period on Javascript Function (ASP.net)


Sorry if duplicated, but I really confused with these javascript. Please help me, if willing.

I have this javascript function that already worked, this function will add thousands separator with commas :

function addCommas(x) {
  //remove commas
  retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;

  //apply formatting
  return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); 
}

And I call this function in the textbox, like this :

 Number Format <asp:TextBox ID="txtPrice" runat="server" onkeyup="this.value=addCommas(this.value);"></asp:TextBox>

The output, looked like this (the separator using commas):

60,000,234

BUT I want the output, looked like this (the separator using period) :

60.000.234

Give me a solution still using these Javascript function, please. Thanks


Solution

  • I notice what was wrong in my code in comment.

    Try this, I used it long time ago.

    function addCommas(x) {
     var retVal=x.toString().replace(/[^\d]/g,'');
      while(/(\d+)(\d{3})/.test(retVal)) {
       retVal=retVal.replace(/(\d+)(\d{3})/,'$1'+'.'+'$2');
     }
     return retVal;
    }
    Number <input type="text" onkeypress="this.value=addCommas(this.value);" onkeyup="this.value=addCommas(this.value);" />

    I hope so this will help You.