如何测试 double 是否等于 NaN?
我在 Java 中有一个 double,我想检查它是否为 NaN。 最好的方法是什么?
I have a double in Java and I want to check if it is NaN
.
What is the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用静态
Double .isNaN(double)
方法,或者您的Double
的.isNaN()
方法。简单地这样做:
还不够,因为 IEEE 对于 NaN 和浮点数的标准 已定义。
Use the static
Double.isNaN(double)
method, or yourDouble
's.isNaN()
method.Simply doing:
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
尝试
Double.isNaN ()
:请注意,[
double.isNaN()
] 将不起作用,因为未装箱的双精度数没有与其关联的方法。Try
Double.isNaN()
:Note that [
double.isNaN()
] will not work, because unboxed doubles do not have methods associated with them.您可能还需要考虑通过
Double.isFinite(value)
检查值是否是有限的。从 Java 8 开始,Double
类中有一个新方法,您可以立即检查值是否不是 NaN 和无穷大。You might want to consider also checking if a value is finite via
Double.isFinite(value)
. Since Java 8 there is a new method inDouble
class where you can check at once if a value is not NaN and infinity.您可以使用
var != var
检查 NaN。NaN
不等于NaN
。编辑:这可能是迄今为止最糟糕的方法。它令人困惑,可读性差,而且总体上是不好的做法。
You can check for NaN by using
var != var
.NaN
does not equalNaN
.EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.
如果您的测试值是Double(不是基元)并且可能是
null
(这显然也不是数字),那么您应该使用以下术语:< code>(value==null || Double.isNaN(value))
因为
isNaN()
想要一个基元(而不是将任何基元双精度装箱为 Double)Double),传递null
值(无法拆箱为 Double)将导致异常,而不是预期的false
。If your value under test is a Double (not a primitive) and might be
null
(which is obviously not a number too), then you should use the following term:(value==null || Double.isNaN(value))
Since
isNaN()
wants a primitive (rather than boxing any primitive double to a Double), passing anull
value (which can't be unboxed to a Double) will result in an exception instead of the expectedfalse
.下面的代码片段将帮助评估持有 NaN 的原始类型。
双 dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ?真:假;
The below code snippet will help evaluate primitive type holding NaN.
double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;
初学者需要实际例子。所以尝试下面的代码。
Beginners needs practical examples. so try the following code.