String format for only one decimal place?

前端 未结 6 1672
天命终不由人
天命终不由人 2020-12-10 10:44

I\'d like to dispaly only one decimal place. I\'ve tried the following:

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


        
相关标签:
6条回答
  • 2020-12-10 11:11

    You need it to be a floating-point value for that to work.

    double thevalue = 6.33;
    

    Here's a demo. Right now, it's just a string, so it'll be inserted as-is. If you need to parse it, use double.Parse or double.TryParse. (Or float, or decimal.)

    0 讨论(0)
  • 2020-12-10 11:15

    Here is another way to format floating point numbers as you need it:

    string.Format("{0:F1}",6.33);
    
    0 讨论(0)
  • 2020-12-10 11:20

    ToString() simplifies the job. double.Parse(theValue).ToString("N1")

    0 讨论(0)
  • 2020-12-10 11:25

    Here are a few different examples to consider:

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

    Output : 6.00

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

    Output : 6.33

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

    Output : 6.46

    0 讨论(0)
  • 2020-12-10 11:35

    Please this:

    String.Format("{0:0.0}", 123.4567); // return 123.5
    
    0 讨论(0)
  • 2020-12-10 11:38

    option 1 (let it be string):

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

    option 2 (convert it):

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

    option 3 (fire up RegEx):

    var regex = new Regex(@"(\d+\.\d)"); // but that everywhere, maybe static
    thevalue = regexObj.Match(thevalue ).Groups[1].Value;
    
    0 讨论(0)
提交回复
热议问题