2011-11-19 122 views
3

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

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

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

回答

6

当然。我已经使用基于a blog post by Matt Weber的技术来完成它。下面是一个使用文化格式货币(小数位等)的示例,但使用货币符号和适用于给定货币代码的小数位数(因此,美国文化中的一百万日元将被格式化为¥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; 
} 
+0

不错!我没有想到你可能也想使用十进制数字的事实,但这显然是有道理的。 – Nitramk