1

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 Answers3

4

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;
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

"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));
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99
0

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