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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…