Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the currency formatting for the current culture for an ASP.NET web application?

The currency decimal and thousand separators for the en-ZA region are ',' and ' ' respectively, but the separators in common use are '.' for decimal, plus my user wants ',' for the thousands separator. I wish to set these globally, so that I only have to use the {0:C} format string for all my currency fields, without having to any explicit Format or ToString calls.

I would prefer to be able to do this without changing the culture settings on the web server, as I also need to set the decimal places for currency to zero, as cents are not wanted when reporting on estimates of R100k and up etc. I wouldn't want to arbitrarily set the whole culture to zero places, just one for this application.

In comments to his answer on this question, Jon Skeet suggests cloning the current culture and setting and changing the required settings. I have done this as follows:

void Application_Start(object sender, EventArgs e)
{
    var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
    newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
    newCulture.NumberFormat.CurrencyGroupSeparator = ",";
}

However, how to I activate that new culture for all requests the application handles from this point on? Is there another way to achieve what I wish to do?

like image 930
ProfK Avatar asked Oct 21 '25 03:10

ProfK


1 Answers

You can use Application_BeginRequest event to set the culture for every request. Inside event:

var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
newCulture.NumberFormat.CurrencyGroupSeparator = ",";

System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;
like image 59
Waqas Avatar answered Oct 23 '25 19:10

Waqas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!