[英]String format for only one decimal place?
我想顯示只有一個小數位。 我嘗試過以下方法:
string thevalue = "6.33";
thevalue = string.Format("{0:0.#}", thevalue);
結果:6.33。 但應該是6.3? 即使0.0也不起作用。 我究竟做錯了什么?
以下是根據需要格式化浮點數的另一種方法:
string.Format("{0:F1}",6.33);
您需要它作為浮點值才能工作。
double thevalue = 6.33;
這是一個演示。 現在,它只是一個字符串,因此它將按原樣插入。 如果需要解析它,請使用double.Parse
或double.TryParse
。 (或float
或decimal
。)
以下是一些需要考慮的不同示例:
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); // return 123.5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.