Check for a double variable

I need to check if I have a data type variable 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 didn’t understand if txtPrice.Textthere was anything other than the number in it, the class Convertwould just parse it.

How can I confidently check if a variable is double?

+5
source share
10 answers

Use this:

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

How can I confidently check if a variable is double?

You need to be clearer about what you are really trying to do here. I don’t think you are asking what you think, what you are asking, and it is worth knowing about the differences in terminology.

, double, a double. , object, ValueType ,

if (value is double)

, , double. double.TryParse - , . , "15,5" double? , , , . ?

, IFormatProvider . , .

, :

double result;
// For suitable values of text, style and culture...
bool valid = double.TryParse(text, style, culture, out result);

valid, , . valid , result . valid , result 0.

+7

Double.TryParse:

double price;
if (Double.TryParse(txtPrice.Text, out price))
{
    Console.WriteLine(price);
}
else
{
    Console.WriteLine("Not a double!");
}
+3

- -

  double doubleVar;
    if( typeof(doubleVar) == double ) {
        printf("doubleVar is of type double!");
    }

, double.

+1

  • double.ParseExact
  • Regex, , .
0
0

, , , ? , , , .

string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum)
MessageBox.Show(Num.ToString());
else
MessageBox.Show("Invalid number");
0

double.TryParse(), false, .

0

:

double.Parse(txtPrice.Text);

?

Exception, : " ". , , .

0

All Articles