How to check if double value is negative or not?

As the name implies, how to check whether a particular is Doublenegative or not. This is how I get the instanceDouble

(Double.parseDouble(data[2])

Thoughts, suggestions?

+3
source share
6 answers
Double v = (Double.parseDouble(data[2]));
if (v<0){
//do whatever?
}
+19
source

Being pedantic < 0will not give you all the 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 negative but not less 0.0

you can use

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

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

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

Note. In IEEE-754, a NaN may have the same signed bit as a negative number.

+27
source

, < 0:

if (Double.parseDouble(data[2]) < 0) {
    // the number is negative
} else {
    // the number is positive
}
+6

Double.parseDouble double (), double. , .

:

if (foo < 0)

, , ,

if (foo >= 0)

- " ". .

+4
Double.parseDouble(data[2]);

Double, Double. Double, autoboxing. , , 0? :

Double.parseDouble(data[2]) < 0;
+2

, ,

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

if (v == Math.abs(v))
{
    //must be positive
}
else
{
    //must be negative
}
0

All Articles