我有一个功能:
string FormatCurrency(string currencyCode, decimal amount)
示例:
Input: "USD", 1230.56
Output: "USD 1,230.56"
Input: "USD", 1230.00
Output: "USD 1,230"
Input: "VND", 1200000
Output: "1.200.000 VND"
我想加入文化格式(包含代码,而不是符号)和自定义格式(“#,##。##”)。 我该如何实施? 感谢
我的代码,我来自互联网:
CultureInfo culture = (from c in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
let r = new RegionInfo(c.LCID)
where r != null
&& r.ISOCurrencySymbol.ToUpper() == currencyCode.ToUpper()
select c).FirstOrDefault();
if (culture == null)
{
return amount.ToString("#,##.##");
}
return string.Format(culture, "{0:C2}", amount);
但输出为“$ 1,200.00”。我的预期结果是“1,200美元”
答案 0 :(得分:3)
有点hackish,但你可以这样做:
CultureInfo culture = (from c in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
let r = new RegionInfo(c.LCID)
where r != null
&& r.ISOCurrencySymbol.ToUpper() == currencyCode.ToUpper()
select c).FirstOrDefault();
if(culture == null)
{
// fall back to current culture if none is found
// you could throw an exception here if that's not supposed to happen
culture = CultureInfo.CurrentCulture;
}
culture = (CultureInfo)culture.Clone();
culture.NumberFormat.CurrencySymbol = currencyCode;
// Add spaces between the figure and the currency code
culture.NumberFormat.CurrencyPositivePattern = culture.NumberFormat.CurrencyPositivePattern == 0 ? 2 : 3;
var cnp = culture.NumberFormat.CurrencyNegativePattern;
switch(cnp)
{
case 0: cnp = 14; break;
case 1: cnp = 9; break;
case 2: cnp = 12; break;
case 3: cnp = 11; break;
case 4: cnp = 15; break;
case 5: cnp = 8; break;
case 6: cnp = 13; break;
case 7: cnp = 10; break;
}
culture.NumberFormat.CurrencyNegativePattern = cnp;
return amount.ToString("C" + ((amount % 1) == 0?"0":"2"), culture);
在这里小提琴:https://dotnetfiddle.net/30f7u3
有关:
FormatCurrency("USD", 1230.56M);
FormatCurrency("USD", 1230.00M);
FormatCurrency("VND", 1200000M);
我明白了:
USD 1,230.56
USD 1,230
1.200.000 VND
答案 1 :(得分:1)
我希望这会对你有所帮助。如果我理解你想要将所有内容显示为当前的文化,那么您只想更改货币的显示方式。
这是基础知识,您可以自行继续。
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.CurrencySymbol = currencyCode;
culture.NumberFormat.CurrencyPositivePattern = 2;
return string.Format(culture, "{0:C2}", amount);
我的结果是42,55美元。
答案 2 :(得分:0)
var output = String.Format ("{0} {1:### ### ##0.00}",currencyCode,amount)
使用文化使用的货币格式
var output = amount.ToString ("C");