Я пытался преобразовать из строки в Int.Неправильный формат ввода показывает - PullRequest
0 голосов
/ 29 апреля 2019

Я пытался преобразовать строку в int для целей расчета.У меня есть total_amount в двойном и unit_quantity в строковом формате.Я хочу изменить строку 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();

Ожидаемый результат - правильный расчет.Но я получаю сообщение об ошибке типа «Введен неверный формат»

Ответы [ 2 ]

1 голос
/ 30 апреля 2019

По сути, вы должны увидеть, какой ввод вы передаете в функцию разбора.

Попробуйте что-то вроде следующего, чтобы увидеть немного больше о том, что происходит.

    // 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
0 голосов
/ 29 апреля 2019

Попробуйте этот код:

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();
...