【问题标题】:Can I get the standard currency format to use a negative sign instead of parentheses?我可以让标准货币格式使用负号而不是括号吗?
【发布时间】:2012-07-28 06:31:08
【问题描述】:

在我的项目中有很多地方我尝试使用内置的{0:C} 货币格式显示货币。如果该数字为负数,则将其包围在括号中的值。我希望它改用负号。

我的 web.config 将文化设置为 auto,它解析为 en-US

理想的解决方案是一些全局 web.config 或其他设置,使 {0:C} 显示 en-US 文化的负号,但我也愿意接受其他不太出色的解决方案。

【问题讨论】:

标签: c# asp.net


【解决方案1】:

您必须指定正确的NumberFormatInfo.CurrencyNegativePattern,它可能是 1。

Decimal dec = new Decimal(-1234.4321);
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
culture.NumberFormat.CurrencyNegativePattern = 1; 
String str = String.Format(culture, "{0:C}", dec);
Console.Write(str);

演示:http://ideone.com/HxSqT

输出:

-$1,234.43

【讨论】:

  • 我认为 CurrencyNegativePattern 应该是 1。在美国,货币符号应该在左侧而不是右侧。
  • @Sam:相应地编辑了我的答案。
  • 5变1肯定很容易。:)
  • @Sam:当然可以。由于他没有提供确切的所需格式,因此由 OP 选择他想要的任何内容。但是这个列表很容易:msdn.microsoft.com/en-us/library/…
【解决方案2】:

我认为这里的答案组合会让你更接近你想要的。

protected void Application_BeginRequest()
{
    var ci = CultureInfo.GetCultureInfo("en-US");

    if (Thread.CurrentThread.CurrentCulture.DisplayName == ci.DisplayName)
    {
        ci = CultureInfo.CreateSpecificCulture("en-US");
        ci.NumberFormat.CurrencyNegativePattern = 1;
        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }
}

如果您不想编写任何代码来处理这样的单一文化...我相信您需要建立自己的文化...Check this Question

【讨论】:

    【解决方案3】:

    据我了解你的问题。

    您希望根据文化显示货币格式。

    每次你做特定文化的事情时,.NET 都会查看Thread.CurrentThread.CurrentCultureThread.CurrentThread.CurrentUICulture

    您可以在 ASP.NET 中的 global.asax BeginRequest 方法中设置所需的文化。

    protected void Application_BeginRequest()
    {
        var ci = CultureInfo.GetCultureInfo("en-US"); // put the culture you want in here
    
        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多