Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
551 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...