Add the correct currency symbol in .NET
You cannot always rely on the browser language as a valid indicator for what currency your visitors use, and sometimes it doesn’t matter because your web application let’s them decide the currency themselves. You then need a little workaround in order to be able to prefix the right currency symbol to a currency number.
If you format a number like this {0:C} for currency, then .NET automatically uses the current culture as an indicator for choosing the currency symbol to prefix the number like this: $40,00. But if you want to be able to specify the currency yourself, the you have to tell the threads current culture what the currency symbol should be.
This is examples of what I want to be able to write out without interfering with the users language settings and dependant or their choice of currency:
$ 40,00
£ 40,00
€ 40,00
DKK 40,00
SEK 40,00
Example
It is not that obvious or well documented how to do it, but after some Googling
I was finally able to figure it out. You have to add the correct currency symbol to
the threads current culture. These small methods was what I came up with:
private void SetCurrencyFormat()
{
string currency = "USD";
//
Clone the current culture
CultureInfo culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
//
Set the currency to the culture
LocalFormat.CurrencySymbol = GetCurrencySymbol(currency);
culture.NumberFormat = LocalFormat;
//
Add the culture to the current thread
Thread.CurrentThread.CurrentCulture = culture;
}
private string GetCurrencySymbol(string currency)
{
switch (currency.ToUpperInvariant())
{
case "USD":
return "$";
case "EUR":
return "€";
case "GBP":
return "£";
default:
return currency;
}
}
This approach works from ASP.NET and Windows Forms and just about anywhere in the
.NET Framework.
Read more about number
formats on MSDN.