与 Double.NaN 相等
我有以下代码...
if (Price_Foreign != Double.NaN)
{
output.Append(spacer);
output.Append(String.Format("{0,-10:C} USD",Price_Foreign));
}
哪个输出:
NaN USD
什么给出?
我使用 Double.NaN 来指示该值不存在,并且不应输出。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许您正在寻找
IsNaN
静态函数?尝试这样的事情:
Perhaps you are looking for the
IsNaN
static function?Try something like this:
IEEE 754 浮点标准规定,比较 NaN 与 NaN 将始终返回假。 如果必须这样做,请使用
Double.IsNaN()
。但是,这并不是完成您想做的事情的最佳方式。 双精度数并不精确,您在这里使用它们来表示价格。 我敢打赌,在某个时候,您也会想要比较价格以获得平等。 这是行不通的,因为你可以'不要依赖浮点相等。
您确实应该考虑对这些值使用某种整数类型(支持相等比较),而不是尝试使用双精度数。 双打用于解决科学问题; 不是为了金融。
The IEEE 754 floating point standard states that comparing NaN with NaN will always return false. If you must do this, use
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.
Double.NaN
不等于任何东西,甚至不等于它本身。请参阅Double.NaN 字段在 .NET Framework 类库文档中:
Double.NaN
is not equal to anything, not even itself.See the Double.NaN Field in the .NET Framework Class Library documentation:
作为背景信息:
IsNaN()
方法的作用是return v != v;
As background information: what the
IsNaN()
method does isreturn v != v;
如果你像我一样懒,可以使用以下扩展方法:
你需要另一个 System.Double 扩展方法。
If you are lazy, like me, you can use the following extension method:
You would need another one for System.Double.