How to format currency value entered in a text box using Javascript and ASP.NET

You might be in a situation where you want to display the value entered by user in a proper currency format e.g. if user entered 10000 and you want to format it like 10,000. In order to do so you’ve to follow these steps:

 

First add a text box in your asp.net page/control

 

<asp:TextBox ID=”txtTotal_Amount” runat=”server”></asp:TextBox>

 

Then add an attribute for OnKeyUp and OnKeyPress events

 

txtTotal_Amount.Attributes.Add(“OnKeyUp”, “OnCurrencyValueKeyUp(this);”);

txtTotal_Amount.Attributes.Add(“OnKeyPress”, “OnCurrencyValueKeyUp(this);”);

 

Now you’ve to define the function OnCurrencyValueKeyUp in order to handle the formatting

 

function OnCurrencyValueKeyUp(input)

{

if(input.value.toString().length == 1 && input.value.toString() == ‘0’)

input.value = input.value.replace(‘0’,”);

 

var num = input.value.replace(‘.’,”);

num = input.value.replace(/,/g,”);

if((!isNaN(num)|| num==’-‘) && num != ‘-0’)

{

if(num.indexOf(‘.’) > -1)

{

num = num.split(‘.’);

num[0] = num[0].toString().split(”).reverse().join(”).replace(/(?=d*.?)(d{3})/g,’$1,’).split(”).reverse().join(”).replace(/^[,]/,”);

if(num[1].length > 2)

{

num[1] = num[1].substring(0,num[1].length-1);

}

input.value = num[0]+’.’+num[1];

}

else

{

input.value = num.toString().split(”).reverse().join(”).replace(/(?=d*.?)(d{3})/g,’$1,’).split(”).reverse().join(”).replace(/^[,]/,”) };

}

else

{

input.value = input.value.substring(0,input.value.length-1);

}

input.value = input.value.toString().replace(/$| /g,”);

input.value = input.value.toString().replace(‘.’,”);

input.value = input.value .toString().replace(‘-,’,’-‘);

 

}

 

That’s it, just run your application and try it. Waiting for your comments on this article