繁体   English   中英

将String转换为int和int转换为String c#

[英]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.#####");
}

它抛出格式异常!

您的代码中有几个问题:

  1. 当字符串为空Convert.ToInt32int.Parse会抛出 Format Exception,因此需要在解析前检查字符串。

  2. doulbe上乘以int结果将是double因此您需要将其存储在double变量中。 将结果转换为 `int' 会导致小数部分出现异常或丢失。

  3. 您不需要使用Convert.ToInt32(txtCarPrice.Text)int.Parse(txtCarPrice.Text)两次解析值。

  4. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM