[英]how to convert a string number with leading 0 to a double in c#
所以我試圖將帶有前導 0 的字符串數字轉換為雙精度,並將 output 轉換為我的文本框,但我不斷收到“不能簡單地將雙精度類型轉換為字符串”。
我嘗試了這兩種方法,但它不起作用:
Double.TryParse(090015.40, out time1);
System.Console.WriteLine("time1 " + time1);
time2 = Convert.ToDouble(090015.60);
System.Console.WriteLine("time2 " + time2);
//textBox_time1.Text = time1;//"cannot simply convert a type double to the string" error
//textBox_time2.Text = time2;//"cannot simply convert a type double to the string" error
控制台上的當前 output:
time1 90015.4
time2 90015.6
output 我想要:
time1 090015.4
time2 090015.6
因此,首先讓我們解釋您遇到的錯誤。 發生錯誤是因為textBox_time1.Text
和textBox_time2.Text
屬性需要字符串而不是雙精度。 您可以在Microsoft Docs中查看詳細信息。
其次,要修復錯誤和您要解決的問題,您可以按照 Lucian 的建議,使用.ToString("000000.0")
將數字格式化為提供的字符串公式並恢復前導零。
我會說,我質疑在已轉換的數字上繼續使用前導零有多大好處,並且還會說,如果您要轉換回的數字,使用上面的公式恢復前導零可能會導致問題字符串比公式允許的長。
希望有幫助!
當您需要它們進行 +、-、*、/ 等數學運算時,您只需要將字符串轉換為 double/int/float。 如果您只想在屏幕上顯示它們(進入文本框或類似的東西),則只需要數字字符串。 這里有一個例子:
private static void ConvertTest()
{
string myString = "13.45";
double myDouble1; //myDouble1 = 0
double myDouble2; //myDouble2 = 0
Double.TryParse(myString, out myDouble1); //myDouble1 = 13.45
myDouble2 = Convert.ToDouble(myString); //myDouble2 = 13.45
Console.WriteLine(myDouble1); //Prints a string
Console.WriteLine(myDouble1 + myDouble2); //Prints the sum of the doubles
Console.WriteLine(myDouble1.ToString() + myDouble2.ToString()); //Prints the first double and then the second --> 13.4513.45
}
希望能幫助到你
如果您希望 output 為雙精度,則前面不能有任何零。 這只能以這種方式以字符串形式輸出。 雙精度格式的內部表示不包括前導零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.