String format for one decimal place?

I would like to tell only one decimal place. I tried the following:

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

result: 6.33. But should it be 6.3? Even 0.0 does not work. What am I doing wrong?

+17
source share
7 answers

For this you need this floating point value.

 double thevalue = 6.33; 

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

+21
source

Here's another way to format floating point numbers as needed:

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

Here are a few different examples:

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

Exit: 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

+13
source

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

+5
source

option 1 (let it be a 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 (run RegEx):

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

Other answers are rounded for me if I chose, say, 6.39 or even something like 6.398925. This approach is to convert to as-is string, then search for the decimal place and return only one number after it:

 double val = 6.39; string truncatedString = val.ToString().Substring(0, val.ToString().IndexOf(".") + 2); Console.WriteLine(truncatedString); //returns 6.3 
+1
source

Please, this:

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

All Articles