检查变量是否为 double 数据类型

2024-04-27

我需要检查我拥有的变量是否属于该数据类型double。这是我尝试过的:

try
{
    double price = Convert.ToDouble(txtPrice.Text);
}
catch (FormatException)
{
    MessageBox.Show("Product price is not a valid price", "Product price error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return false;
}

我认为这会起作用,但显然,我没有意识到如果txtPrice.Text里面除了数字之外还有任何东西,Convert类只会解析它。

如何可靠地检查变量是否为双精度型?


用这个:

double price;
bool isDouble = Double.TryParse(txtPrice.Text, out price);
if(isDouble) {
  // double here
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检查变量是否为 double 数据类型 的相关文章