【问题标题】:Currency formatting - Windows Store Apps货币格式 - Windows 应用商店应用
【发布时间】:2013-01-29 10:46:16
【问题描述】:

在以前的 .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 类型 - 没有 @ 987654335@ 过载 - 在某些情况下会导致一些有趣的值错误。

那么如何在 WinRT.net 中动态格式化货币呢?

【问题讨论】:

  • 所以我不是唯一一个认为 CurrencyFormatter 应该接受小数作为参数的人。

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


【解决方案1】:

我发现您仍然可以在 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);
}

这给出了预期的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多