【发布时间】:2012-08-27 16:47:12
【问题描述】:
我只想显示一位小数。我尝试了以下方法:
string thevalue = "6.33";
thevalue = string.Format("{0:0.#}", thevalue);
结果:6.33。但应该是6.3?即使 0.0 也不起作用。我做错了什么?
【问题讨论】:
我只想显示一位小数。我尝试了以下方法:
string thevalue = "6.33";
thevalue = string.Format("{0:0.#}", thevalue);
结果:6.33。但应该是6.3?即使 0.0 也不起作用。我做错了什么?
【问题讨论】:
你需要它是一个浮点值才能工作。
double thevalue = 6.33;
Here's a demo. 现在只是一个字符串,所以它会按原样插入。如果需要解析,请使用double.Parse 或double.TryParse。 (或float,或decimal。)
【讨论】:
0.155 这样的数字四舍五入到0.2..不过这是一个小问题!
这是另一种根据需要格式化浮点数的方法:
string.Format("{0:F1}",6.33);
【讨论】:
这里有几个不同的例子可供考虑:
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
【讨论】:
ToString() 简化了工作。
double.Parse(theValue).ToString("N1")
【讨论】:
选项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" 呢?
请这个:
String.Format("{0:0.0}", 123.4567); // return 123.5
【讨论】: