Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a variable is of data type double

Tags:

c#

casting

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;
}

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?

like image 546
James Dawson Avatar asked Mar 22 '12 14:03

James Dawson


People also ask

How do you check if a value is double or not in C#?

IsNan() can determine whether a value is not-a-number."); // This will return true. if Double. IsNaN(0. / zero) then printfn "Double.


2 Answers

Use this:

double price;
bool isDouble = Double.TryParse(txtPrice.Text, out price);
if(isDouble) {
  // double here
}
like image 193
ionden Avatar answered Oct 02 '22 22:10

ionden


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.

like image 40
dougajmcdonald Avatar answered Oct 02 '22 20:10

dougajmcdonald