Sunday, April 19, 2015

Get currency format using Google in ASP.NET

Many of times I have encountered by a vital question, "How to change 20000.00 to $20,000.00". This is nothing but a simple currency formatter. You can use either jquery or server side coding to show the currency in this format. Here in this post I will show you how to format the currency input from user in ASP.NET.

Format Currency using JQuery:
First start with JQuery. Google has provided a very simple way to format currency. You can find it out from here. Or you can follow this one.

To continue you have to download two js files. One is jquery.formatCurrency-1.4.0.js and second one is jquery.min.js. I have attached these js files with the code I have attached along with this post.

So lets start with sample coding. First create a new project and add a new page, named it whatever you want. Then add a new text box. Firstly we will do it with onBlur function of jquery, so we don't need any more extra button for showing our formatted currency.

Add those downloaded js files into your header section of web form. And the paste the following code into your page.

<script src="jquery.min.js"></script>
<script src="jquery.formatCurrency-1.4.0.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $('.text').focusout(function () {

Now copy the text box.

     <p>Currency Formatter</p>
     <asp:TextBox runat="server" ID="txtPrice" CssClass="text"></asp:TextBox>
     Show by Jquery: <span class="currencyLabel"></span>

Check the CssClass of text box. Its the thing by which formatCurrency() method is calling to format it to text box and also show the output value to a span.

Format Currency using C#:
I hope its clear to you how to format currency by JQuery, now lets see how to do this such using C#. Don't worry C# has an inbuilt function for this. For C# we are taking an extra button to display the output into a label.

<asp:TextBox ID="txtCurrency" runat="server"></asp:TextBox>
<asp:Button ID="btnChange" Text="Format" runat="server" OnClick="btnChange_Click"    />
<asp:Label ID="lblShow" runat="server"></asp:Label>

C# Code:

protected void btnChange_Click(object sender, EventArgs e)
    lblShow.Text = (Convert.ToDouble(txtCurrency.Text)).ToString("C2");

Make sure this method is only applicable to  data type like decimal and double. So you have to add a checking whether user input is bound to numbers.

Download the full source code here.


Post a Comment

Popular Posts