将一个带前导0的字符串数字转换为双数 c#。

问题描述 投票:0回答:1

所以,我试图将一个带前导0的字符串数字转换为双数,并将其输出到我的文本框中,但我一直得到 "不能简单地将一个类型的双数转换为字符串"。

我尝试了这2种方法,但它不工作。

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

c# string forms type-conversion double
1个回答
1
投票

所以,首先让我们解释一下你所得到的错误。出现这个错误是因为 textBox_time1.TexttextBox_time2.Text 属性需要一个字符串,而不是一个双数。你可以在 Microsoft Docs.

其次,为了解决你想解决的错误和问题,你可以像Lucian建议的那样,使用 .ToString("000000.0") 这将格式化数字到提供的字符串公式,并恢复前导零。

我想说的是,我质疑在你已经转换的数字上继续使用前导零有多大的好处,也想说的是,如果你要转换回字符串的数字比公式允许的要长,使用上面的公式来恢复前导零可能会导致问题。

希望能帮到你!


0
投票

只有当你需要它们进行+,-,*,等数学运算时,你才需要将字符串转换为双intfloat。如果你只想在屏幕上显示它们(进入文本框或类似的东西),你只需要数字的字符串。下面是一个例子。


    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

    }

希望对你有帮助


-1
投票

如果你想输出的是双倍的,前面就不能有零。这样只能以字符串的方式输出。双倍格式的内部表示不包括前导零。

© www.soinside.com 2019 - 2024. All rights reserved.