我想解析我的字符串以加倍。我的問題是newTime的結果是800,但結果應該是8,00。C#如何解析一個字符串以加倍
string time = "08:00";
double newTime = double.Parse(time.Replace(':', '.'));
我想解析我的字符串以加倍。我的問題是newTime的結果是800,但結果應該是8,00。C#如何解析一個字符串以加倍
string time = "08:00";
double newTime = double.Parse(time.Replace(':', '.'));
的Double.Parse
結果是Double
,而不是字符串。您需要使用ToString
從雙精度輸出一個字符串。
您還應該使用Double.Parse
的過載參數NumberStyles
。使用Float
值允許指數表示法。
string time = "08:00";
double newTime = double.Parse(time.Replace(':', '.'), CultureInfo.InvariantCulture);
你的問題是,你的文化有一個不同的小數點分隔符,你正在你的字符串中創建。
如果你要正確對待:
作爲小數點分隔你可以把它改成這個
string time = "08:00";
double newTime = double.Parse(time.Replace(":", Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator));
newTime仍然是8.但我想要8,00 –
@AH然後你想要一個字符串。如果有雙精度,雙精度將只顯示小數 –
,只是做:
string time = "08:00";
// when parsing "time", decimal separator is ":"
double newTime = double.Parse(time,
new NumberFormatInfo() { NumberDecimalSeparator = ":" });
嘗試與魔術常量避免技巧如time.Replace(':', '.')
中的'.'
。請注意,newTime
將是8
,而不是8.00
(自8 == 8.0 == 8.00 == 8.000...
)。如果你想代表newTime
小數點後使用數字格式化:
// F2 - format string ensures 2 digits after the decimal point
// Outcome: 8.00
Console.Write(newTime.ToString("F2"));
'8,00'不是一個有效的雙 – Liam
我得到'8'當我執行你的代碼 –
你想達到什麼目的?從HH:mm格式計算小時數? – MadOX