Adding thousands separators to numbers

In one of the projects I'm working on, there was a requirement that numbers entered in a webform should be formatted to add thousands separator to them. So I came up with these couple of functions, one to allow only numbers to be entered in the textbox, another to add thousands separator to the entered number.


function FilterKeys(TextBox, e)
{
        var TextBoxContent = TextBox.value;
        var strCheck = '1234567890';
        var whichCode = (window.Event) ? e.which : e.keyCode;

        if (whichCode == 13 || whichCode == 37 || whichCode==39 || whichCode==9) return true;  // Enter
            key = String.fromCharCode(whichCode);  // Get key value from key code
        if (strCheck.indexOf(key) == -1)
            // Not a valid key    
            e.returnValue = false;
                    
}
      
      

function AddThousandsSeparator(TextBox, e)
{
        var TextBoxContent = TextBox.value;                  
        var temp="";
        TextBoxContent=TextBoxContent.split(',').join('');
                    
        s=TextBoxContent.split('').reverse();
                    

        for(i=0;i<s.length;i++)
            {
                if((i)%3==0 && i!=0)
                temp+=',';
                temp+=s[i];
                    
            }
            
        var formattedString=temp.split('').reverse().join('');
         TextBox.value=formattedString;
        return true


}

Using these 2 functions is pretty simple. Here's an example

<asp:TextBox id="TextBox1" runat="server" onkeypress="FilterKeys(this,event)" onkeyup="AddThousandsSeparator(this,event)"></asp:TextBox>
Published Monday, February 20, 2006 12:35 AM by admin
Filed Under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

What do you think?

(required) 
required 
optional
required