【问题标题】:Globally changing format of negative currency numbers in C#C# 中负货币数字的全局变化格式
【发布时间】:2010-10-22 07:03:10
【问题描述】:

我们有一个大型 ASP.NET MVC 项目,其中所有输出到屏幕的数字都被格式化为货币(即 ToString("c"))。但是,负数显示为 ()。例如:

decimal d = -8.88m;
Console.WriteLine(d.ToString("c"));
//outputs $(8.88)

这对我们的用户来说有点烦人,尤其是因为在文本框中。我们有几千个地方可以像这样将货币字段发送到屏幕上,所以我们想要一种在全球范围内更改格式的方法。有吗?我见过的所有方法都表明你必须创建一个新的格式化程序,类似于这样:

 string curCulture = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
 System.Globalization.NumberFormatInfo currencyFormat =
     new System.Globalization.CultureInfo(curCulture).NumberFormat;
 currencyFormat.CurrencyNegativePattern = 1;

我们不希望更改所有 ToString("c") 方法...有更好的方法吗?我的第一个想法是将我们的语言环境更改为澳大利亚,但意识到日期格式会被搞砸。

【问题讨论】:

    标签: c# asp.net c#-4.0


    【解决方案1】:

    Aliostad 很接近……在你的基本控制器中试试这个:

            System.Globalization.CultureInfo modCulture = new System.Globalization.CultureInfo("en-US");
            modCulture.NumberFormat.CurrencyNegativePattern = 1;
            Thread.CurrentThread.CurrentCulture = modCulture;
    

    【讨论】:

      【解决方案2】:

      你在正确的轨道上。但是不要创建新的格式化程序,而是更改当前线程的否定格式:

        // update: dont use this!
        Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyNegativePattern = 1;
      

      您可以在发起请求时放置它,并且在 ASP.NET 中只有一个线程负责处理请求,因此这将影响您的所有货币格式(除非您自己创建一个新线程,在这种情况下您拥有选项来改变它)。

      更新

      是的,上面不起作用,因为它是只读的!试试这个:

                  Console.WriteLine((-111.98).ToString("c"));
                  CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
                  CultureInfo newCulture = new CultureInfo(currentCulture.IetfLanguageTag);
                  newCulture.NumberFormat.CurrencyNegativePattern = 1;
                  Thread.CurrentThread.CurrentCulture = newCulture;
                  Console.WriteLine((-111.98).ToString("c"));
      

      【讨论】:

      • 我很兴奋,但这不起作用 - 我收到了 InvalidOperationException ...“实例是只读的”
      • 嗨,Jess,我实际上没有尝试过,我怀疑该行中的某些内容将是只读的。查看我的更新。
      • 是的,这行得通。我将对方的答案标记为正确,因为他是第一个。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 2015-07-27
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      相关资源
      最近更新 更多