代码之家  ›  专栏  ›  技术社区  ›  Prabhu

如何正确地舍入和格式化小数?[副本]

  •  3
  • Prabhu  · 技术社区  · 14 年前

    可能重复:
    c# - How do I round a decimal value to 2 decimal places (for output on a page)

    我正试图用四位小数来显示我的小数。数据库将我的数字四舍五入到小数点后4位,但它返回带有尾随0的数字(由于字段的小数精度),因此类似于9.45670000。然后,当我这样做的时候:

    string.Format("{0:#,#.####}", decimalValue);
    

    我在页面上得到的输出是9.4567,这就是我想要的。

    但是,如果从db返回的数字是9.45600000,则执行该格式后的输出是9.456

    但我要展示的是9.4560

    我如何格式化我的小数,使小数位数总是四位?

    更新:另外,如果我希望动态确定小数位数,是否可以使用变量(而不是.0000)?

    4 回复  |  直到 14 年前
        1
  •  13
  •   theChrisKent    14 年前
    string.Format("{0:N4}",decimalValue);
    

    Standard Numeric Format Strings

    Custom Numeric Format Strings

    要动态设置精度,可以执行以下操作:

    double value = 9.4560000;
    int precision = 4;
    string format = String.Format("{{0:N{0}}}",precision);
    string valuestring = String.Format(format, value);
    
        2
  •  1
  •   Gabe    14 年前
    string.Format({0:#,#0.0000}, decimalValue); 
    
        3
  •  1
  •   Vishal    14 年前

    使用 String.Format -

        decimal d =123.47
        string specifier="{0:0,0.0000}"; // You need to get specifier dynamically here..
        String.Format(specifier, d);      // "123.4700"
    
        4
  •  1
  •   wageoghe    14 年前

    试试这个:

    string.Format("{0:#,###.0000}", 9.45600000);
    

    在格式中添加零将强制输出零(如果没有要放置的数字)。

    要用编程方式驱动的零数添加零,可以执行以下操作:

      int x = 5;
      string fmt = "{0:#,###." + new string('0', x) + "}";
      string.Format(fmt, 9.456000000);