Java 检查双精度值是否大于零的简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39040900/
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
Simple way to check if double value is greater than zero
提问by Pirate_Hyman
I have a double variable(employeeSalary) and I want to check if this value is greater than(>) zero(0). I can think of very naive way to write this code but I am not sure if for doubledata type this is correct way to write.
我有一个双变量(employeeSalary),我想检查这个值是否大于(>)零(0)。我可以想到编写此代码的非常幼稚的方法,但我不确定对于双数据类型这是否是正确的编写方式。
if(employeeSalary > 0){
// Employee salary is greater than zero.
}else{
// Employee salary is less than or equal to zero.
}
Can anyone please tell me if this approach works?
谁能告诉我这种方法是否有效?
回答by OldCurmudgeon
There are danger areas when comparing double
values but using >
or <
is not a problem. Your code should work perfectly.
比较double
值时存在危险区域,但使用>
or<
不是问题。您的代码应该可以完美运行。
You should, however, be wary of using ==
as there are many edge cases where a number that seems to be 0
is not (e.g. -0.0
) and a number is effectively zero (e.g. 0.0000...001
) but comparing with == 0
will fail.
但是,您应该小心使用==
,因为在许多边缘情况下,似乎0
不是的数字(例如-0.0
)和数字实际上为零(例如0.0000...001
)但与 比较== 0
将失败。
回答by Michael Peacock
If you're just wanting to compare primitives, you can certainly do something like:
如果您只是想比较原语,您当然可以执行以下操作:
if(employeeSalary > 0.0){
// Employee salary is greater than zero.
}else{
// Employee salary is less than or equal to zero.
}
Note that, if employeeSalary is a double (primitive) then you should really compare this to other double rather than an int.
请注意,如果employeeSalary 是double(原始),那么您应该真正将其与其他double 而不是int 进行比较。
You could also use a couple Double static methods to do the same
你也可以使用几个 Double 静态方法来做同样的事情
// assuming employeeSalary is a double
if(Double.compare(employeeSalary, Double.valueOf(0.0)) > 0 ){
// Employee salary is greater than zero.
}else{
// Employee salary is less than or equal to zero.
}
See: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare(double,%20double)
请参阅:https: //docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare(double,%20double)