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;
}
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?
Use this:
You can use
double.TryParse()
it will returnfalse
if it couldn't create a double.You may use
double.ParseExact
orSo if I get your question right, you mean you only want to allow numbers right? If that's true, then maybe this will help you.
Double.TryParse is what you want.
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 adouble
. If you've got a variable which is declared to be of typeobject
,ValueType
or one of the interfaces it supports, then you can useBut it sounds like what you really want to know is whether a string value is parseable as a
double
. For that, you should usedouble.TryParse
- but you also need to think about what culture you're interested in. For example, would you view "15,5" as a validdouble
? 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:
Then use the
valid
variable to determine whether or not it was actually parsed correctly. Ifvalid
is true, then the value ofresult
is the parsed value. Ifvalid
is false,result
will be 0.