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?
IsNan() can determine whether a value is not-a-number."); // This will return true. if Double. IsNaN(0. / zero) then printfn "Double.
Use this:
double price;
bool isDouble = Double.TryParse(txtPrice.Text, out price);
if(isDouble) {
// double here
}
Couldn't you just use:
double.Parse(txtPrice.Text);
?
With this you will a FormatException saying "Input string was not in a correct format." if the string value isn't a double, which looks to be roughly what you were doing manually anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With