如何测试 double 是否等于 NaN?

问题描述 投票:0回答:7

我在Java中有一个double,我想检查它是否是

NaN
。 最好的方法是什么?

java double equality nan
7个回答
523
投票

使用静态

Double.isNaN(double)
方法,或您的
Double
.isNaN()
方法。

// 1. static method
if (Double.isNaN(doubleValue)) {
    ...
}
// 2. object's method
if (doubleObject.isNaN()) {
    ...
}

简单地做:

if (var == Double.NaN) {
    ...
}
由于

NaN 和浮点数的 IEEE 标准的定义方式,还不够


51
投票

尝试

Double.isNaN()

如果此 Double 值是非数字 (NaN),则返回 true,否则返回 false。

请注意,[

double.isNaN()
] 不起作用,因为未装箱的双精度数没有与其关联的方法。


21
投票

您可能还想考虑通过

Double.isFinite(value)
检查值是否有限。从 Java 8 开始,
Double
类中有一个新方法,您可以立即检查一个值是否不是 NaN 和无穷大。

/**
 * Returns {@code true} if the argument is a finite floating-point
 * value; returns {@code false} otherwise (for NaN and infinity
 * arguments).
 *
 * @param d the {@code double} value to be tested
 * @return {@code true} if the argument is a finite
 * floating-point value, {@code false} otherwise.
 * @since 1.8
 */
public static boolean isFinite(double d)

10
投票

您可以使用

var != var
检查 NaN。
NaN
不等于
NaN

编辑:这可能是迄今为止最糟糕的方法。这很令人困惑,可读性很差,而且总体来说是不好的做法。


1
投票

如果您的测试值是 Double (不是基元)并且可能是

null
(这显然也不是数字),那么您应该使用以下术语:

(value==null || Double.isNaN(value))

由于

isNaN()
想要一个原语(而不是将任何原语双精度装箱为 Double),因此传递
null
值(无法将其拆箱为 Double)将导致异常,而不是预期的异常
false


0
投票

下面的代码片段将有助于评估持有 NaN 的原始类型。

double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;


-3
投票

初学者需要实际例子。所以尝试下面的代码。

public class Not_a_Number {

public static void main(String[] args) {
    String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";        
    String dottedLine = "------------------------------------------------";     

    Double numerator = -2.0;
    Double denominator = -2.0;      
    while (denominator <= 1) {
        Double x = numerator/denominator;           
        Double y = new Double (x);
        boolean z = y.isNaN();
        System.out.println("y =  " + y);
        System.out.println("z =  " + z);
        if (z == true){
            System.out.println(message);                
        }
        else {
            System.out.println("Hi, everyone"); 
        }
        numerator = numerator + 1;
        denominator = denominator +1;
        System.out.println(dottedLine);         
    } // end of while

} // end of main

} // end of class
© www.soinside.com 2019 - 2024. All rights reserved.