How to check if Double value is negative or not? [

2019-04-28 12:51发布

As title suggests, how do i check if particular Double is negative or not. Here is how am getting Double instance

(Double.parseDouble(data[2])

Thoughts, suggestions?

标签: java double
6条回答
叼着烟拽天下
2楼-- · 2019-04-28 12:56

You could test if it is < 0:

if (Double.parseDouble(data[2]) < 0) {
    // the number is negative
} else {
    // the number is positive
}
查看更多
我只想做你的唯一
3楼-- · 2019-04-28 12:58
Double.parseDouble(data[2]);

Doesn't give you a Double, it returns a double. If you are assigning it to a Double, it gets there via autoboxing. Anyways to see if it is negative compare it to 0? As in:

Double.parseDouble(data[2]) < 0;
查看更多
等我变得足够好
4楼-- · 2019-04-28 13:03

Being pedantic, < 0 won't give you all negative numbers.

double d = -0.0;
System.out.println(d + " compared with 0.0 is " + Double.compare(d, 0.0));
System.out.println(d + " < 0.0 is " + (d < 0.0));

prints

-0.0 compared with 0.0 is -1
-0.0 < 0.0 is false

-0.0 is negative but not less than 0.0

You can use

public static boolean isNegative(double d) {
     return Double.compare(d, 0.0) < 0;
}

A more efficient, if more obtuse, version is to check the signed bit.

public static boolean isNegative(double d) {
     return Double.doubleToRawLongBits(d) < 0;
}

Note: Under IEEE-754 a NaN can have the same signed bit as a negative number.

查看更多
可以哭但决不认输i
5楼-- · 2019-04-28 13:04
Double v = (Double.parseDouble(data[2]));
if (v<0){
//do whatever?
}
查看更多
对你真心纯属浪费
6楼-- · 2019-04-28 13:09

Another possible solution that I quite like is

Double v = Double.parseDouble(data[2]);

if (v == Math.abs(v))
{
    //must be positive
}
else
{
    //must be negative
}
查看更多
Animai°情兽
7楼-- · 2019-04-28 13:11

Double.parseDouble returns a double (primitive) not a Double. In this case it doesn't really matter, but it's worth being aware of.

You can use:

if (foo < 0)

to check whether a value is negative - but be aware that this isn't the opposite of

if (foo >= 0)

due to "not a number" values. It does work with infinite values though.

查看更多
登录 后发表回答