Search code examples
c#stringdoublereal-number

How to check if the value of string variable is double


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?


Solution

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