我正在尝试从字符串转换为整数。输入的格式不正确

时间:2019-04-29 12:07:11

标签: c# asp.net wpf code-behind

出于计算目的,我试图从字符串转换为int。我所拥有的是double形式的total_amount和字符串格式的unit_quantity。我想将Unit_quantity字符串更改为int。这两个值均取自数据库,total_amount的数据类型为float,unit_quantity的数据类型为string。

我尝试了普通的int.parse选项,但它不起作用。

        double UnitAmt = double.Parse(TextboxunitAmt.Text);
        string UnitQty = TextboxunitQty.Text.ToString();

        int Qty = int.Parse(UnitQty);
        double GrandTotal = UnitAmt * Qty;

        TextboxCostPrice.Text = GrandTotal.ToString();

预期结果是正确的计算。但是我得到的是一个类似“输入格式不正确”的错误

2 个答案:

答案 0 :(得分:1)

本质上,您必须查看要传递给解析函数的输入。

尝试以下类似方法,以了解发生了什么事。

    // Lets try parsing some random strings into doubles.
    // Each one with varying cases.
    string[] testStrings = new string[]{"$32.43", "342", "1,332", "0.93", "123,432.34", "boat"};
    foreach (string ts in testStrings)
    {
        double newValue;
        if (double.TryParse(ts, out newValue))
        {
            // for WPF, you can use a MessageBox or Debug.WriteLine
            Console.WriteLine("We were able to successfully convert '" + ts + "' to a double! Here's what we got: " + newValue);
        }
        else
        {
            // for WPF, you can use a MessageBox or Debug.WriteLine
            Console.WriteLine("We were unable to convert '" + ts + "' to a double");
        }
    }

这是您应该看到的输出:

We were unable to convert '$32.43' to a double
We were able to successfully convert '342' to a double! Here's what we got: 342
We were able to successfully convert '1,332' to a double! Here's what we got: 1332
We were able to successfully convert '0.93' to a double! Here's what we got: 0.93
We were able to successfully convert '123,432.34' to a double! Here's what we got: 123432.34
We were unable to convert 'boat' to a double

答案 1 :(得分:-4)

尝试此代码:

.subscribe()