Monday, June 11, 2007

Currency Format Depending on Culture

It is usual, that you write an application with GUI for a specified culture and then you suddenly get to know that the application should work with several different currency formats. In the following example I want to demonstrate a very simple method how to change the currency format in your application elegantly and dynamically.

Ordinarily numbers are formatted as currency by these ways:

decimal value = 1234567.89M;

Console.WriteLine(value.ToString("C"));

//or

Console.WriteLine("{0:C}", value);

//or

Console.WriteLine(String.Format("{0:C}", value));


Actually, there are many places like this in your application and you want to change the format depending on user's choice of culture. The following code comes in handy:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");


The whole example is:

using System;

using System.Threading;

using System.Globalization;

 

namespace CurrencyFormat

{

  class Program

  {

    static void Main()

    {

      decimal value = 1234567.89M;

      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

      Console.WriteLine("{0:C}", value);

      Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

      Console.WriteLine("{0:C}", value);     

      Thread.CurrentThread.CurrentCulture = new CultureInfo("ja-JP");

      Console.WriteLine("{0:C}", value);

    }

  }

}


Output:

$1,234,567.89

1 234 567,89 €

Y1,234,568


List of all available culture names and identifiers is on MSDN.

kick it on DotNetKicks.com

No comments: