简体   繁体   中英

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?

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

"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));
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM