Change Current Thread’s Currency Symbol

Consider the following code. It shows how a decimal value is converted into a string that contains an amount and a currency symbol.

var value = 1099.99m;
Console.WriteLine("{0:C}", value);

// Output: 1,099.99 $

What if we wanted to output a different currency symbol (e.g. “USD”, “€” or “Darsek”) but keep the current number formatting and culture info? If you try the following code, you will probably get an InvalidOperationException stating that the “Instance is read-only“.

Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol = "Darsek";

This happens because usually the current thread’s culture info is set to a read-only instance that cannot be modified. You will need to create a new instance of CultureInfo. Thankfully, there is a method called “Clone” that we can use to create a new CultureInfo instance with the same properties as the current culture.

var culture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
culture.NumberFormat.CurrencySymbol = "Darsek";
Thread.CurrentThread.CurrentCulture = culture;

var value = 1099.99m;
Console.WriteLine("{0:C}", value);

// Output: 1,099.99 Darsek

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s