在以前的 .Net 生涯中,我为当前语言格式化货币(任何货币)的方式是这样做的:
public string FormatCurrencyValue(string symbol, decimal val)
{
var format = (NumberFormatInfo)CultureInfo.CurrentUICulture.NumberFormat.Clone();
//overwrite the currency symbol with the one I want to display
format.CurrencySymbol = symbol;
//pass the format to ToString();
return val.ToString("{0:C2}", format);
}
该函数返回给定货币符号格式化的货币值,不包含任何小数部分,并根据当前文化进行调整 - 例如,在en-GB
中为£50.00
,但在fr-FR
中为50,00£
。
在Windows Store下运行相同的代码会产生{50:C}
。
查看(相当糟糕的)WinRT文档后,我们确实有CurrencyFormatter类 - 但是只有在尝试使用"£"
作为参数并获得ArgumentException
(WinRT文档非常特殊 - 它几乎没有关于异常的信息)之后才意识到它需要一个ISO货币符号(公平地说,参数名称是currencyCode
,但即便如此)。
现在 - 我也可以获取其中之一,但是CurrencyFormatter
还有另一个问题,使其不适用于货币格式 - 您只能格式化double
、long
和ulong
类型 - 没有decimal
重载 - 这可能导致某些情况下出现一些有趣的值错误。
那么如何在WinRT.net中动态格式化货币呢?