简体   繁体   中英

String format for only one decimal place?

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

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

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

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

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

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 .)

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

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

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;

请这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM