Get Currency Format Using Google In ASP.NET

Introduction

Many times, I have encountered a vital question: "How can I change 20000.00 to $20,000.00?" This involves 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 out about it from here. Or you can follow this.

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

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

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

JS

  1. <script src="jquery.min.js"></script>  
  2. <script src="jquery.formatCurrency-1.4.0.js"></script>  
  3. <script type="text/javascript">  
  4.         $(document).ready(function () {  
  5.             $('.text').focusout(function () {  
  6.                 $('.text').formatCurrency();  
  7.                 $('.text').formatCurrency('.currencyLabel');  
  8.             });  
  9.         });         
  10. </script>  

HTML

  1. <div>  
  2.      <p>Currency Formatter</p>  
  3.      <asp:TextBox runat="server"   
  4.   
  5.      ID="txtPrice" CssClass="text"></asp:TextBox>  
  6.      Show by Jquery: <span class="currencyLabel"></span>  
  7. </div>  

Check the CssClass of text box. It's the method 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 it's clear to you how to format currency by jQuery. Now, let's see how to do this 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.

  1. <asp:TextBox ID="txtCurrency" runat="server"></asp:TextBox>  
  2. <asp:Button ID="btnChange" Text="Format" runat="server" OnClick="btnChange_Click"   />  
  3. <asp:Label ID="lblShow" runat="server"></asp:Label>  
  4.   
  5. protected void btnChange_Click(object sender, EventArgs e)  
  6. {  
  7.     lblShow.Text = (Convert.ToDouble(txtCurrency.Text)).ToString("C2");  
  8. }  

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


Similar Articles