May 21, 2019 11:00 by
Peter
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.js. I 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
<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 () {
$('.text').formatCurrency();
$('.text').formatCurrency('.currencyLabel');
});
});
</script>
HTML
<div>
<p>Currency Formatter</p>
<asp:TextBox runat="server"
ID="txtPrice" CssClass="text"></asp:TextBox>
Show by Jquery: <span class="currencyLabel"></span>
</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.
<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>
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 types like decimal and double. So you have to add a check to see whether user input is bound to numbers.