gpt4 book ai didi

c# - C# 中的自定义货币格式

转载 作者:行者123 更新时间:2023-11-30 20:37:28 25 4
gpt4 key购买 nike

我有一个函数:

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 美元”

最佳答案

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

在这里 fiddle :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

关于c# - C# 中的自定义货币格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36005332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com