我试图从字符串转换为 int 以进行计算。我拥有的是 double 格式的 total_amount 和 string 格式的 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();
预期的结果是正确的计算。但我得到的是“输入格式不正确”之类的错误
本质上,您必须查看您传递给解析函数的输入。
尝试类似以下的操作,以了解更多正在发生的事情。
// 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句