Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

double

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?

like image 751
Rachel Avatar asked May 01 '12 15:05

Rachel


People also ask

Can double be a negative number?

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.

Can you have a negative double in Java?

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.

Can double take negative values in C#?

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. It occupies 8 bytes in the memory.


3 Answers

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.

like image 143
Peter Lawrey Avatar answered Oct 18 '22 13:10

Peter Lawrey


Double v = (Double.parseDouble(data[2]));
if (v<0){
//do whatever?
}
like image 42
sjakubowski Avatar answered Oct 18 '22 14:10

sjakubowski


You could test if it is < 0:

if (Double.parseDouble(data[2]) < 0) {
    // the number is negative
} else {
    // the number is positive
}
like image 38
Darin Dimitrov Avatar answered Oct 18 '22 14:10

Darin Dimitrov