Checking if a variable is of data type double

后端 未结 10 1180
無奈伤痛
無奈伤痛 2021-02-08 02:19

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         


        
相关标签:
10条回答
  • 2021-02-08 02:52

    Why dont you try something like this -

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

    This can easily check if the variable is of a type double .

    0 讨论(0)
  • 2021-02-08 02:54

    Use this:

    double price;
    bool isDouble = Double.TryParse(txtPrice.Text, out price);
    if(isDouble) {
      // double here
    }
    
    0 讨论(0)
  • 2021-02-08 02:54

    You could also use .GetType() to return the type of the variable if you are unsure what is being returned if a method is being called to generate the number. See http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx for an example.

    0 讨论(0)
  • 2021-02-08 02:56

    Use the Double.TryParse method:

    double price;
    if (Double.TryParse(txtPrice.Text, out price))
    {
        Console.WriteLine(price);
    }
    else
    {
        Console.WriteLine("Not a double!");
    }
    
    0 讨论(0)
提交回复
热议问题