c# - 货币格式 - Windows 应用商店应用

标签 c# .net windows-runtime windows-store-apps

在以前的 .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-GB50,00£ fr-FR

在 Windows 应用商店下运行的相同代码会生成 {50:C}

查看(相当糟糕的)WinRT 文档,我们确实有 CurrencyFormatter类 - 但它只是在尝试以 "£" 作为参数触发构造函数并获得 ArgumentException 之后(WinRT 文档非常特殊 - 它几乎没有任何信息关于异常),我意识到它需要一个 ISO 货币符号(公平地说,参数名称是 currencyCode,但即便如此)。

现在 - 我也可以获得其中之一,但是 CurrencyFormatter 有另一个问题使其不适合货币格式化 - 你只能格式化 doublelongulong 类型 - 没有 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/

相关文章:

c# - WP8.1和WP10的区别

c# - LINQ 取查询中多个字段的平均值

.net - Int32.TryParse(String, Int32) 是否会在失败时更改 int 参数?

.net - 使用Windows Runtime异步文件API来确保顺序文件访问?

c# - 如何修改列表属性而不影响同类型的其他列表属性?

c# - 如果 "Presenter"在 "View"上设置属性是否违反了 MVP 模式?

c# - 如何允许在 ListView/GridView 项控件内进行操作,同时允许在 ListView/GridView 上进行滚动和横向滑动操作?

c# - Linq-To-Entities 'Contains' 子句 1-many 关系

javascript - 将 Javascript 转换为 C# 问题

泛型问题中的 C# 继承