Wednesday, September 3, 2008

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 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];
input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') };
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


Anastácio Soberbo said...

Hello, I like this blog.
Sorry not write more, but my English is not good.
A hug from Portugal

Anonymous said...

Youre awesome :)
thank you so much dude ;)

Anonymous said...

Thank You So much dude !!

Adeel Nasir said...

Thanks man, its a pleasure for me to be helpful to someone...:)

Vishnuvardhan said...

Thanks a lot for writing this piece of good
its working for me

Anonymous said...

Nice, it works really well. Many thanks!

Adeel Nasir said...

Than you all...:)