.NET中的货币格式化

3
我正在了解.NET框架中货币格式化的工作原理。据我所知,Thread.CurrentCulture.NumberFormatInfo.CurrencySymbol包含本地文化的货币符号。
但实际上,在现实世界中,并不存在明确的一对一关系,将特定的文化与货币符号联系起来。例如,我可能位于英国,但我的发票是用欧元开具的。或者我可能住在冰岛,但从美国供应商那里收到以美元计价的发票。或者我可能住在瑞典,但我的银行账户使用欧元。我意识到,在某些情况下,您可能只想假定当地货币是要使用的货币,但通常情况并非如此。
在这些情况下,我应该克隆CultureInfo并在克隆上手动设置货币符号,然后在格式化金额时使用克隆吗?即使货币符号无效,我认为仍然有必要使用NumberFormatInfo的其他属性,如CurrencyDecimalSeparator。
1个回答

6
当然可以。我使用基于Matt Weber的博客文章的技术来完成它。这里有一个示例,它使用你所在文化的货币格式(小数位等),但使用适用于特定货币代码的货币符号和小数位数(因此在en-US文化中,一百万日元的格式为¥1,000,000)。
当然,您可以修改它以选择保留当前文化和货币文化的哪些属性。
public static NumberFormatInfo GetCurrencyFormatProviderSymbolDecimals(string currencyCode)
{
    if (String.IsNullOrWhiteSpace(currencyCode))
        return NumberFormatInfo.CurrentInfo;


    var currencyNumberFormat = (from culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                                let region = new RegionInfo(culture.LCID)
                                where String.Equals(region.ISOCurrencySymbol, currencyCode,
                                                    StringComparison.InvariantCultureIgnoreCase)
                                select culture.NumberFormat).First();

    //Need to Clone() a shallow copy here, because GetInstance() returns a read-only NumberFormatInfo
    var desiredNumberFormat = (NumberFormatInfo)NumberFormatInfo.GetInstance(CultureInfo.CurrentCulture).Clone();
    desiredNumberFormat.CurrencyDecimalDigits = currencyNumberFormat.CurrencyDecimalDigits;
    desiredNumberFormat.CurrencySymbol = currencyNumberFormat.CurrencySymbol;

    return desiredNumberFormat;
}

不错!我没有想到你可能也想使用小数位数,但这显然是有道理的。 - Nitramk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接