C# 与 Double.NaN 相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/558267/
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
Equality with Double.NaN
提问by Chris Cudmore
I have the following code...
我有以下代码...
if (Price_Foreign != Double.NaN)
{
output.Append(spacer);
output.Append(String.Format("{0,-10:C} USD",Price_Foreign));
}
Which outputs:
哪些输出:
NaN USD
What gives?
是什么赋予了?
I'm using Double.NaN to indicate that the value doesn't exist, and shouldn't be output.
我使用 Double.NaN 表示该值不存在,不应输出。
采纳答案by Andrew Hare
Perhaps you are looking for the IsNaN
static function?
也许您正在寻找IsNaN
静态函数?
Try something like this:
尝试这样的事情:
if (!Double.IsNaN(Price_Foreign))
{
output.Append(spacer);
output.Append(String.Format("{0,-10:C} USD",Price_Foreign));
}
回答by Todd Gamblin
The IEEE 754 floating point standardstates that comparing NaN with NaN will alwaysreturn false. If you must do this, use Double.IsNaN()
.
在IEEE 754浮点标准规定,与南NaN的比较将始终返回false。如果您必须这样做,请使用Double.IsNaN()
.
But, this isn't the best way to do what you're trying to do. Doubles are NOT precise, and you're using them to represent prices here. I'm betting that at some point, you're going to want to compare prices for equality, too. That's not going to work, because you can't rely on floating point equality.
但是,这不是做您想做的事情的最佳方式。双打并不精确,您在这里使用它们来表示价格。我敢打赌,在某些时候,您也会想要比较价格的平等性。那是行不通的,因为你不能依赖浮点相等。
You should really look into using some integer type for these values (that supports equality comparison) rather than trying to use doubles. Doubles are for scientific problems; not for finance.
您应该真正考虑为这些值使用一些整数类型(支持相等比较),而不是尝试使用双精度数。双打是为了科学问题;不是为了金融。
回答by Grant Wagner
Double.NaN
is not equal to anything, not even itself.
Double.NaN
不等于任何东西,甚至不等于它本身。
See the Double.NaN Fieldin the .NET Framework Class Library documentation:
请参阅.NET Framework 类库文档中的Double.NaN 字段:
Use IsNaNto determine whether a value is not a number. It is not possible to determine whether a value is not a number by comparing it to another value equal to NaN.
使用IsNaN确定值是否不是数字。无法通过将某个值与另一个等于 NaN 的值进行比较来确定该值是否不是数字。
回答by Martijn Courteaux
As background information: what the IsNaN()
method does is return v != v;
作为背景信息:该IsNaN()
方法的作用是return v != v;