仅保留一位小数的字符串格式?

30

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

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

结果为:6.33。但应该是6.3吗?甚至0.0也不行。我做错了什么?

6个回答

34

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

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

30

你需要将它转换成浮点数才能让它工作。

double thevalue = 6.33;

这里有一个演示。 目前它只是一个字符串,所以会按原样插入。如果你需要解析它,请使用 double.Parsedouble.TryParse。(或者使用 floatdecimal。)


1
它的表现完美,但会将像 0.155 这样的数字四舍五入为 0.2。不过这只是一个小问题! - Anirudha

21

以下是几个需要考虑的不同示例:

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


6
重点是分享信息并帮助人们,我发现这很有用。 - reggaeguitar

15

ToString() 简化了工作。

double.Parse(theValue).ToString("N1")

2
它的功能完美,但会将数字四舍五入,例如0.155会变成0.2...不过这只是一个小问题! - Anirudha

1

Please this:

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

1

选项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;

1
如果 thevalue"6.333" 呢? - Tim Schmelter
1
你甚至可以使用“Match(..).Value”。 - TheHe
1
正则表达式和字符串选项不会四舍五入到最接近的数字,它们会截断。 - Tim S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接