格式化当前文化的任何货币和金额(不是货币文化)

时间:2016-01-17 17:59:31

标签: .net localization number-formatting globalization currency-formatting

我需要格式化任何给定货币的金额,以使其在当前文化中看起来符合预期。

例如,在英国文化(en-GB)中,人们期望看到以下内容:

1.00£ $ 1.00包装 €1.00

在德国文化中,相同的货币金额应显示为:

1,00£ 1,00 $ 1,00€

我找到了一种方法(下面)根据与货币相关的文化格式(例如£1.00,1,00€)格式化货币/金额但这不太正确,因为来自英国的人即使欧元不是与en-GB相关的货币,也会看到1.00欧元。

public static string FormatCurrency(this decimal amount, string currencyCode)
{
    var 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("0.00");

    return string.Format(culture, "{0:C}", amount);
}

根据当前的文化,任何人都可以提供或描述以任何给定货币查看金额的方法吗?

1 个答案:

答案 0 :(得分:1)

要将当前符号设置为所需的符号(£,$,€或其他任何内容),同时仍使用当前文化的其他属性,您只需克隆当前的NumberFormatInfo并替换货币符号:

var cultureInfo = Thread.CurrentThread.CurrentCulture;
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need

var price = 12.3m;
var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".