【问题标题】:String format for only one decimal place?字符串格式只有一位小数?
【发布时间】:2012-08-27 16:47:12
【问题描述】:

我只想显示一位小数。我尝试了以下方法:

string thevalue = "6.33";
thevalue = string.Format("{0:0.#}", thevalue);

结果:6.33。但应该是6.3?即使 0.0 也不起作用。我做错了什么?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    你需要它是一个浮点值才能工作。

    double thevalue = 6.33;
    

    Here's a demo. 现在只是一个字符串,所以它会按原样插入。如果需要解析,请使用double.Parsedouble.TryParse。 (或float,或decimal。)

    【讨论】:

    • 它工作得很好,但它会将像0.155 这样的数字四舍五入到0.2..不过这是一个小问题!
    【解决方案2】:

    这是另一种根据需要格式化浮点数的方法:

    string.Format("{0:F1}",6.33);
    

    【讨论】:

      【解决方案3】:

      这里有几个不同的例子可供考虑:

      double l_value = 6;
      string result= string.Format("{0:0.00}", l_value );
      Console.WriteLine(result);
      

      输出:6.00

      double l_value = 6.33333;
      string result= string.Format("{0:0.00}", l_value );
      Console.WriteLine(result);
      

      输出:6.33

      double l_value = 6.4567;
      string result = string.Format("{0:0.00}", l_value);
      Console.WriteLine(result);
      

      输出:6.46

      【讨论】:

      • 重点是分享信息和帮助人们,我觉得这很有帮助。
      【解决方案4】:

      ToString() 简化了工作。 double.Parse(theValue).ToString("N1")

      【讨论】:

      • 它运行良好,但会将 0.155 之类的数字四舍五入到 0.2。不过这是一个小问题!
      【解决方案5】:

      选项1(让它成为字符串):

      string thevalue = "6.33";
      thevalue = string.Format("{0}", thevalue.Substring(0, thevalue.length-1));
      

      选项2(转换它):

      string thevalue = "6.33";
      var thevalue = string.Format("{0:0.0}", double.Parse(theValue));
      

      选项 3(启动 RegEx):

      var regex = new Regex(@"(\d+\.\d)"); // but that everywhere, maybe static
      thevalue = regexObj.Match(thevalue ).Groups[1].Value;
      

      【讨论】:

      • 如果thevalue"6.333" 呢?
      • 你甚至可以使用“Match(..).Value”
      • 正则表达式和字符串选项不会四舍五入到最接近的数字,它们会被截断。
      【解决方案6】:

      请这个:

      String.Format("{0:0.0}", 123.4567); // return 123.5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2018-05-11
        • 2018-06-20
        • 1970-01-01
        • 2013-09-16
        • 2013-09-29
        • 1970-01-01
        相关资源
        最近更新 更多