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?
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?
Double v = (Double.parseDouble(data[2]));
if (v<0){
//do whatever?
}
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.
You could test if it is < 0
:
if (Double.parseDouble(data[2]) < 0) {
// the number is negative
} else {
// the number is positive
}
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.
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;
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
}