检查变量的数据类型是否为double [英] Checking if a variable is of data type double

查看:106
本文介绍了检查变量的数据类型是否为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查我拥有的变量是否为数据类型 double 。这是我尝试的方法:

I need to check if a variable I have is of the data type double. This is what I tried:

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 类都将解析出来。

I thought this would work, but obviously, I failed to realize if txtPrice.Text had anything other than a number in it, the Convert class will just parse it out.

如何切实地检查变量是否为双精度值?

How can I realiably check if a variable is a double?

推荐答案

使用此命令:

double price;
bool isDouble = Double.TryParse(txtPrice.Text, out price);
if(isDouble) {
  // double here
}

这篇关于检查变量的数据类型是否为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆