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?
There are no unsigned floating-point data types. On all machines, variables of the float, double, and long double data types can store positive or negative numbers.
One of the tricky parts of this question is that Java has multiple data types to support numbers like byte, short, char, int, long, float, and double, out of those all are signed except char, which can not represent negative numbers.
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. It occupies 8 bytes in the memory.
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.
Double v = (Double.parseDouble(data[2]));
if (v<0){
//do whatever?
}
You could test if it is < 0
:
if (Double.parseDouble(data[2]) < 0) {
// the number is negative
} else {
// the number is positive
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With