我试图从字符串转换为 int。输入格式不正确显示

I was trying to convert from string to int. Input was not in correct format is showing

出于计算目的,我试图将字符串转换为整数。我拥有的是 total_amount 双精度和 unit_quantity 字符串格式。我想将 Unit_quantity 字符串更改为 int。这两个值都取自数据库,total_amount 的数据类型为浮点型,unit_quantity 的数据类型为字符串。

我已经尝试了正常的 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();

预期的结果是正确的计算。但是我得到的是 "Input was not in a correct format"

这样的错误

试试这个代码:

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

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

TextboxCostPrice.Text = GrandTotal.ToString();

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

尝试如下所示的操作,以了解更多情况。

    // Lets try parsing some random strings into doubles.
    // Each one with varying cases.
    string[] testStrings = new string[]{".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 '.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