Formatting Currency in ASP.NET

Formatting Currency in ASP.NET in most cases is a very easy to do task, however it baffles many. Users fail to understand the importance of Culture and UICulture as well as the difference between them.

The UICulture property determines the resource files loaded for a page. The Culture property determines how strings such as currency, dates etc are formatted. A culture name For eg: en-US consists of two parts. The first part(en) is the language code and the second part(US) is the country/region code. If you do not specify the country or region code, then you have specified something called a neutral culture.

You can set either the UICulture or Culture properties by using the <%@ Page %> directive or you can set these properties globally in the web configuration file as shown below:


  <globalization culture="en-GB" uiCulture="en-GB" />




Let's take a simple example where we will format a string to represent Great Britain's currency formatting

Add this to your page directive


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestArea6.aspx.cs"


Inherits="TestArea6" Culture="en-GB" %>




C#


protected void Page_Load(object sender, EventArgs e)


{


    decimal revenue = 1452.66m;


    string str = String.Format("{0:C}", revenue);


    Response.Write(str);


}




VB.NET


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


    Dim revenue As Decimal = 1452.66D


    Dim str As String = String.Format("{0:C}", revenue)


    Response.Write(str)


End Sub




Output: £1,452.66




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: