How to get specific culture currency pattern

naishx picture naishx · Aug 3, 2011 · Viewed 33.5k times · Source

How do i get the currency pattern for a specific culture?

For Example:

Instead of using:

string.Format("{0:c}", 345.10)

I want to use this:

string.Format("#.##0,00 €;-#.##0,00 €", 345.10);

But how do i get the pattern string (like "#.##0,00 €;-#.##0,00 €") for each culture my application needs?

I cant use the "{0:c}" pattern because if the user switches the language the currency should be the same.

Answer

Martin Liversage picture Martin Liversage · Aug 3, 2011

A CultureInfo contains a NumberFormatInfo and this class describes (among other things) how to format currency for that particular culture.

In particular you can use CurrencyPositivePattern and CurrencyNegativePattern to determine if the currency symbol is placed before or after the amount and of course CurrencySymbol to get the correct currency symbol. All this information is used by .NET when the C format specifier is used.

You can read more about the NumberFormatInfo class on MSDN.

The code below demonstrates some of the steps required to format currency properly. It only uses CurrencySymbol, CurrencyPositivePattern and CurrencyDecimalDigits and thus is incomplete:

var amount = 123.45M;
var cultureInfo = CultureInfo.GetCultureInfo("da-DK");

var numberFormat = cultureInfo.NumberFormat;
String formattedAmount = null;
if (amount >= Decimal.Zero) {
  String pattern = null;
  switch (numberFormat.CurrencyPositivePattern) {
    case 0:
      pattern = "{0}{1:N" + numberFormat.CurrencyDecimalDigits + "}";
      break;
    case 1:
      pattern = "{1:N" + numberFormat.CurrencyDecimalDigits + "}{0}";
      break;
    case 2:
      pattern = "{0} {1:N" + numberFormat.CurrencyDecimalDigits + "}";
      break;
    case 3:
      pattern = "{1:N" + numberFormat.CurrencyDecimalDigits + "} {0}";
      break;
  }
  formattedAmount = String.Format(cultureInfo, pattern, numberFormat.CurrencySymbol, amount);
}
else {
  // ...
}

Console.WriteLine(formattedAmount);

Of course you could simply use:

var amount = 123.45M;
var cultureInfo = CultureInfo.GetCultureInfo("da-DK");
var formattedAmount = String.Format(cultureInfo, "{0:C}", amount);
Console.WriteLine(formattedAmount);