.NET中的货币格式

Nit*_*amk 3 c# formatting currency

我试图了解货币格式在.NET框架中的工作原理.据我了解,Thread.CurrentCulture.NumberFormatInfo.CurrencySymbol包含本地文化的货币符号.

但正如我所看到的,在现实世界中,特定文化与货币符号之间并没有明确的一对一关系.例如,我可能位于英国,但我用欧元计算我的发票.或者我可能住在冰岛,并以美元收到美国供应商的发票.或者我可能住在瑞典,但我的银行账户使用欧元.我意识到,在某些情况下,您可能只想假设本地货币是要使用的货币,但通常情况并非如此.

在这些情况下,我是否会克隆CultureInfo并在克隆上手动设置货币符号,然后在格式化金额时使用克隆?即使货币符号无效,我认为使用NumberFormatInfo的其他属性仍然有意义,例如CurrencyDecimalSeparator.

Dan*_*n J 6

绝对.我使用了一种基于Matt Weber的博客文章的技术.这是一个使用您的文化格式的货币(小数位等)的示例,但使用适合给定货币代码的货币符号和小数位数(因此,en-US文化中的100万日元将被格式化为¥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;
}
Run Code Online (Sandbox Code Playgroud)