Java 如何将双精度值设置为“非值”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2948444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you set a double value to a "non-value"
提问by Ankur
I have two double data elements in an object.
我在一个对象中有两个双数据元素。
Sometimes they are set with a proper value and sometimes not. When the form field from which they values are received is not filled I want to set them to some value that tells me, during the rest of the code that the form fields were left empty.
有时它们设置了适当的值,有时则没有。当接收它们值的表单字段未填充时,我想将它们设置为某个值,在其余代码中,表单字段留空。
I can't set the values to null as that gives an error, is there some way I can make them 'Undefined'.
我无法将值设置为 null,因为这会产生错误,有什么方法可以使它们“未定义”。
PS. Not only am I not sure that this is possible, it might not also make sense. But if there is some best practice for such a situation I would be keen to hear it.
附注。我不仅不确定这是否可行,而且可能也没有意义。但是,如果有针对这种情况的最佳实践,我会很想听听。
采纳答案by Jon Skeet
Two obvious options:
两个明显的选择:
- Use
Doubleinstead ofdouble. You can then usenull, but you've changed the memory patterns involved substantially. Use a "not a number" (NaN) value:
double d = 5.5; System.out.println(Double.isNaN(d)); // false d = Double.NaN; System.out.println(Double.isNaN(d)); // trueNote that some other operations on "normal" numbers could give you NaN values as well though (0 divided by 0 for example).
- 使用
Double代替double。然后您可以使用null,但您已经大大改变了所涉及的内存模式。 使用“非数字”(NaN) 值:
double d = 5.5; System.out.println(Double.isNaN(d)); // false d = Double.NaN; System.out.println(Double.isNaN(d)); // true请注意,对“正常”数字的其他一些操作也可以为您提供 NaN 值(例如,0 除以 0)。

