【问题标题】:Format any currency and amount for current culture (not culture of the currency)格式化当前文化的任何货币和金额(不是货币的文化)
【发布时间】:2016-04-22 20:29:31
【问题描述】:

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

例如,在英国文化 (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);
}

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

【问题讨论】:

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


    【解决方案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".
    

    【讨论】:

    • 我已经接受了这个解决方案,因为它对我的用例来说是可以接受的。需要注意的是,对于特定文化,货币符号可以出现在金额之前或之后,例如1.00 英镑但 100 克朗(瑞典克朗)。然而,对于英国用户来说,100 克朗似乎不是不可接受的。
    • 有趣。不确定“kr100”是否不可接受(1.00 美元和 1.00 英镑 1.00 欧元绝对正确),但如果是这种情况,那就是语言环境格式的限制。货币格式说明了符号的位置(之前/之后)以及小数点和千位分隔符是什么,但它是万能的。它假定所有货币都有相同的位置。
    • 其实我说过 kr100 不会是不可接受的,即它是可以接受的。为令人困惑的措辞道歉。我同意
    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多