简体   繁体   English

如何检查字符串变量的值是否为double

[英]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. 我正在尝试检查字符串变量的值是否为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. 我已经看到了这个现有的问题( 检查变量是否为数据类型double ),它的答案很不错,但是我有一个不同的问题。

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. 从我上面的代码中,当ValueToTest为“-∞”时,我在变量Test中获得的输出为“ -Infinity”,并且该方法返回true。

When the ValueToTest is "NaN" the output I get is "NaN". 当ValueToTest为“ NaN”时,我得到的输出为“ NaN”。

Are they both "-∞" and "NaN" double values in C#? 它们在C#中都是“-∞”和“ NaN”双精度值吗?

Also is there a way to check for only real numbers ( https://en.wikipedia.org/wiki/Real_number ) and exclude infinity and NaN? 还有一种方法可以只检查实数( https://en.wikipedia.org/wiki/Real_number )并排除无穷和NaN吗?

Yes, they are valid values for double : See the documentation . 是的,它们是double有效值:请参阅文档

Just update your method to include the checks on NaN and Infinity : 只需更新您的方法以包括对NaNInfinity的检查:

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 . "NaN""-∞"是可解析为double有效字符串。 So you need to filter them out if you don't want them to be treated as valid double values: 因此,如果您不希望将它们视为有效的double值,则需要将它们过滤掉:

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. 检查此Double是否具有infinity和inNan检查,希望会得到。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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