字符串格式只有一个小数位?
我想显示只有一个小数位。 我尝试过以下方法:
string thevalue = "6.33"; thevalue = string.Format("{0:0.#}", thevalue);
结果:6.33。 但应该是6.3? 即使0.0也不起作用。 我究竟做错了什么?
你需要它作为一个浮点值才能工作。
double thevalue = 6.33;
这是一个演示。 现在,它只是一个字符串,因此它将按原样插入。 如果需要解析它,请使用double.Parse
或double.TryParse
。 (或float
或decimal
。)
以下是根据需要格式化浮点数的另一种方法:
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;
请这:String.Format(“{0:0.0}”,123.4567); //返回123.5