How to check if the value of string variable is double

8.4k Views Asked by At

I am trying to check if the value of a string variable is double.

I have seen this existing question (Checking if a variable is of data type double) and it's answers and they are great but I have a different question.

public static bool IsDouble(string ValueToTest) 
    {
            double Test;
            bool OutPut;
            OutPut = double.TryParse(ValueToTest, out Test);
            return OutPut;
    }

From my code above, when the ValueToTest is "-∞" the output I get in variable Test is "-Infinity" and the method returns true.

When the ValueToTest is "NaN" the output I get is "NaN".

Are they both "-∞" and "NaN" double values in C#?

Also is there a way to check for only real numbers (https://en.wikipedia.org/wiki/Real_number) and exclude infinity and NaN?

3

There are 3 best solutions below

0
On BEST ANSWER

Yes, they are valid values for double: See the documentation.

Just update your method to include the checks on NaN and Infinity:

public static bool IsDoubleRealNumber(string valueToTest)
{
    if (double.TryParse(valueToTest, out double d) && !Double.IsNaN(d) && !Double.IsInfinity(d))
    {
        return true;
    }

    return false;
}
0
On

"NaN" and "-∞" are valid strings parseable to double. So you need to filter them out if you don't want them to be treated as valid double values:

public static bool IsValidDouble(string ValueToTest)
{
    return double.TryParse(ValueToTest, out double d) && 
           !(double.IsNaN(d) || double.IsInfinity(d));
}
0
On

Check this Double have infinity and inNan checks, hope this will get.

 if (Double.IsInfinity(SampleVar))
{
  //Put your  logic here.
}
if (Double.IsNaN(SampleVar))
{
  //Put your  logic here.
}