2017-02-20 30 views
-6

我想解析我的字符串以加倍。我的問題是newTime的結果是800,但結果應該是8,00。C#如何解析一個字符串以加倍

string time = "08:00"; 
double newTime = double.Parse(time.Replace(':', '.')); 
+2

'8,00'不是一個有效的雙 – Liam

+2

我得到'8'當我執行你的代碼 –

+1

你想達到什麼目的?從HH:mm格式計算小時數? – MadOX

回答

0

Double.Parse結果是Double,而不是字符串。您需要使用ToString從雙精度輸出一個字符串。

您還應該使用Double.Parse的過載參數NumberStyles。使用Float值允許指數表示法。

0
string time = "08:00"; 
double newTime = double.Parse(time.Replace(':', '.'), CultureInfo.InvariantCulture); 
0

你的問題是,你的文化有一個不同的小數點分隔符,你正在你的字符串中創建。

如果你要正確對待:作爲小數點分隔你可以把它改成這個

string time = "08:00"; 
double newTime = double.Parse(time.Replace(":", Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)); 
+0

newTime仍然是8.但我想要8,00 –

+0

@AH然後你想要一個字符串。如果有雙精度,雙精度將只顯示小數 –

1

,只是

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"));