[英]conversion of String to int and int to String c#
我正在尝试计算汽车价格。 我尝试获取汽车价格并将其转换为 int,然后将 int 值乘以百分比,然后在另一个文本框中显示结果。
这是我所做的,它抛出异常:
private void button1_Click(object sender, EventArgs e)
{
int carPrice = Convert.ToInt32(txtCarPrice.Text);
carPrice = int.Parse(txtCarPrice.Text);
int downPayment = Convert.ToInt32(txtDownPayment.Text);
downPayment = int.Parse(txtDownPayment.Text);
downPayment = Convert.ToInt32(carPrice * .2);
txtDownPayment.Text = downPayment.ToString("0.#####");
}
它抛出格式异常!
您的代码中有几个问题:
当字符串为空Convert.ToInt32
和int.Parse
会抛出 Format Exception,因此需要在解析前检查字符串。
在doulbe
上乘以int
结果将是double
因此您需要将其存储在double
变量中。 将结果转换为 `int' 会导致小数部分出现异常或丢失。
您不需要使用Convert.ToInt32(txtCarPrice.Text)
和int.Parse(txtCarPrice.Text)
两次解析值。
txtDownPayment
值未使用,因此您无需读取和解析它。
我想你需要这样的东西:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtCarPrice.Text))
return;
int carPrice = Convert.ToInt32(txtCarPrice.Text);
double downPayment = carPrice * .2;
txtDownPayment.Text = downPayment.ToString("0.#####");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.