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

问题描述 投票:-1回答:2

我试图将字符串转换为int以进行计算。我所拥有的是double_alount in double和unit_quantity in string format。我想将Unit_quantity字符串更改为int。两个值都取自数据库,total_amount的数据类型为float,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();

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

c# asp.net wpf code-behind
2个回答
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

-4
投票

试试这段代码:

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();
© www.soinside.com 2019 - 2024. All rights reserved.