【问题标题】:String.Format with infinite precision and at least 2 decimal digitString.Format 具有无限精度和至少 2 个十进制数字
【发布时间】:2018-02-22 10:46:48
【问题描述】:

我正在为一些对数值准确性非常挑剔的人开发一个应用程序(他们正在处理会计和非常准确的电信变量等问题)。出于这个原因,我在任何地方都使用decimal 类型,因为 float 和 double 类型不合适(不要犹豫,将我重定向到现有的更好的数据类型)。

当我需要格式化这些数字时,我的问题就出现了。要求是根据需要显示尽可能多的十进制数字,但至少要显示 2 位,并且还要使用千位的组分隔符。

例如:

Value       Formatted
1                1.00
1000         1,000.00
1.5              1.50
1000.355    1,000.355
0.000035     0.000035

所以我去 MSDN 寻找数字字符串格式。我发现这个有用的资源Standard Numeric Formats 但我的尝试都没有按预期工作(N、N2、F、F2、G、G2 等,即使我不相信它们,我也尝试了各种组合 ^^ - 我什至尝试一些 F2# 的乐趣)。

我的结论是没有内置格式可以做我想做的事。 对吗?

所以我查看了下一章Custom Numeric Formats。但我找不到适合我需要的组合。所以我去了 SO 并找到了很多关于这个的问题(12 等等)。

这些问题让我担心,唯一的解决方案就是这个:#,##0.00#######,加上我需要的精确度。

我说的对吗?

我猜用 12 #,我的家伙不会发现任何准确性问题,但我可能错过了我需要的神奇格式?

【问题讨论】:

    标签: c# .net formatting string-formatting


    【解决方案1】:

    这可能就是你要找的:

    static string FormatNumber(string input)
    {
        var dec = decimal.Parse(input);
        var bits = decimal.GetBits(dec);
        var prec = bits[3] >> 16 & 255;
        if (prec < 2)
            prec = 2;
        return dec.ToString("N" + prec);
    }
    

    当您调用它时,对小数执行ToString(),并在需要时将结果转换回十进制。

    我尝试了你的示例数字,结果:

    基于this SO answer

    【讨论】:

      【解决方案2】:

      我创建了一个小函数:它根据小数位数来格式化数字:

          public static void Main()
          {
              decimal theValue;
              theValue = 0.000035M;
              Console.WriteLine(theFormat(theValue));
              theValue = 1.5M;
              Console.WriteLine(theFormat(theValue));
              theValue = 1;
              Console.WriteLine(theFormat(theValue));                 
          }
          public static decimal theFormat(decimal theValue){
              int count = BitConverter.GetBytes(decimal.GetBits(theValue)[3])[2];
              return count > 1?theValue:Convert.ToDecimal(string.Format("{0:F2}", theValue));
          }
      

      这会产生以下输出:

      0.000035
      1.50
      1.00
      

      【讨论】:

        【解决方案3】:

        如果您想完全控制格式,您可以为小数实现自己的 IFormatProvider。在其中,您可以使用 StringBuilder 并做任何您需要的事情,而不受 string.Format() 的限制。

        【讨论】:

          猜你喜欢
          • 2020-02-05
          • 1970-01-01
          • 1970-01-01
          • 2011-05-08
          • 2012-03-25
          • 1970-01-01
          • 1970-01-01
          • 2018-01-20
          • 2020-12-23
          相关资源
          最近更新 更多