在以前的 .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);
}
这将返回货币值,不带任何小数部分,针对给定的货币符号进行格式化,并针对当前文化进行调整 - 例如50.00 英镑
en-GB
但50,00£
fr-FR
。
在 Windows 应用商店下运行的相同代码会生成 {50:C}
。
查看(相当糟糕的)WinRT 文档,我们确实有 CurrencyFormatter类 - 但它只是在尝试以 "£"
作为参数触发构造函数并获得 ArgumentException
之后(WinRT 文档非常特殊 - 它几乎没有任何信息关于异常),我意识到它需要一个 ISO 货币符号(公平地说,参数名称是 currencyCode
,但即便如此)。
现在 - 我也可以获得其中之一,但是 CurrencyFormatter
有另一个问题使其不适合货币格式化 - 你只能格式化 double
,long
和 ulong
类型 - 没有 decimal
重载 - 在某些情况下会导致一些有趣的值错误。
那么如何在 WinRT.net 中动态格式化货币呢?
最佳答案
我发现您仍然可以在 NumberFormatInfo
类中使用旧式格式字符串 - 只是,令人费解的是,当您使用 ToString
时它不起作用>。如果您改为使用 String.Format
,那么它就可以工作。
所以我们可以将问题中的代码重写为:
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 String.Format
return string.Format(format, "{0:C2}", val);
}
这给出了期望的结果。
关于c# - 货币格式 - Windows 应用商店应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14581093/