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);
}
c
How can I realiably check if a variable is a double?
You need to be clearer about what you're really trying to do here. I don't think you're asking what you think you're asking, and it's worth being aware of the differences in terminology.
If you've got a variable which is declared to be of type double
, then it's definitely a double
. If you've got a variable which is declared to be of type object
, ValueType
or one of the interfaces it supports, then you can use
if (value is double)
But it sounds like what you really want to know is whether a string value is parseable as a double
. For that, you should use double.TryParse - but you also need to think about what culture you're interested in. For example, would you view "15,5" as a valid double
? European users might, but US users probably wouldn't. Do you want to allow thousands separators?
I would strongly advise you to use the overload which takes an IFormatProvider
and use the appropriate culture. Even if the culture you're interested is the default, it's worth being explicit about that.
You probably want:
double result;
// For suitable values of text, style and culture...
bool valid = double.TryParse(text, style, culture, out result);
Then use the valid
variable to determine whether or not it was actually parsed correctly. If valid
is true, then the value of result
is the parsed value. If valid
is false, result
will be 0.