Nullable double NaN comparison in C#

后端 未结 4 1771
独厮守ぢ
独厮守ぢ 2021-01-12 18:03

I have 2 nullable doubles, an expected value and an actual value (let\'s call them value and valueExpected). A percentage is found using 100 * (value / valueExpected). Howev

相关标签:
4条回答
  • 2021-01-12 18:33

    You can also use

    if (!Double.IsNaN(myDouble ?? 0.0))
    

    The value in the inner-most parenthesis is either the myDouble (with its Nullable<> wrapping removed) if that is non-null, or just 0.0 if myDouble is null. Se ?? Operator (C#).

    0 讨论(0)
  • 2021-01-12 18:42

    With C# 7.0 Pattern matching combined null + NaN check check can be written like this:

    double? d = whatever;
    if(d is double val && double.IsNaN(val))
       Console.WriteLine(val);
    

    The advantage is local scoped variable val at hand, which is not null, nor double.NaN and can even be used outside of if.

    0 讨论(0)
  • 2021-01-12 18:51

    With all Nullable<T> instances, you first check the bool HasValue property, and then you can access the T Value property.

    double? d = 0.0;        // Shorthand for Nullable<double>
    if (d.HasValue && !Double.IsNaN(d.Value)) {
        double val = d.Value;
    
        // val is a non-null, non-NaN double.
    }
    
    0 讨论(0)
  • 2021-01-12 18:53

    I had the same issue and I solved it with casting the double? with double

    double.IsNaN((double)myDouble)
    

    this will return true if NaN and false if not

    0 讨论(0)
提交回复
热议问题