Search code examples
c#stringformstype-conversiondouble

how to convert a string number with leading 0 to a double in c#


so I'm trying to convert a string number with leading 0 to a double and output it to my textbox, but I keep getting a "cannot simply convert a type double to the string".

i tried these 2 ways but it does not work:

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

current output on the console:

time1 90015.4
time2 90015.6

output I want:

time1 090015.4
time2 090015.6


Solution

  • So, first things first lets explain the error you are getting. The error occurs because the textBox_time1.Text and textBox_time2.Text properties require a string rather than a double. You can see details of this over at Microsoft Docs.

    Secondly, to fix the both the error and the problem you are looking to solve you can, as has been suggested by Lucian, use .ToString("000000.0") which will format the number to the string formula provided and restore the leading zero.

    I will say, I question how beneficial it is to continue using a leading zero on a number you've converted, and also will say that using the formula above to restore the leading zero could lead to issues if the number you are converting back to a string is longer than the formula allows.

    Hope that helps!