如何在 C# 中将前导 0 的字符串数字转换为双精度数

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

所以我试图将前导 0 的字符串数字转换为双精度并将其输出到我的文本框,但我一直收到 "cannot simply convert a type double to the string".

我试过这两种方法,但都不行:

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

控制台当前输出:

time1 90015.4
time2 90015.6

我想要的输出:

time1 090015.4
time2 090015.6

如果你希望输出是double,前面不能有任何零。这只能以这种方式在字符串中输出。双精度格式的内部表示不包括前导零。

所以,首先让我们解释一下您遇到的错误。发生错误是因为 textBox_time1.TexttextBox_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

    }

希望对您有所帮助