Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for a negative zero in Java 8?

Tags:

java

java-8

I've been trying to figure out how to determine if a double value is -0.0d. I googled the problem for a bit and found a few different approaches, however all the threads I found were at least a couple years old and seem to no longer work.

Here's what I've tried so far:

double x, y;
x = 0;
y = -0;

println(x == y);
println(Double.compare(x, y) == 0);
println(new Double(x).equals(new Double(y)));
println(Double.doubleToLongBits(x) == Double.doubleToLongBits(y));
println(Math.signum(x) == Math.signum(y));

All of those print true, unfortunately.

The reason I need to distinguish between 0 and -0, if you're wondering, is because I'm trying to parse a double value from user input, and using -0 as a sentinel value in case of an exception.

like image 250
Axim Avatar asked Oct 08 '16 14:10

Axim


People also ask

How to check if a number is negative in Java?

If number<0 the number is negative. If a number is neither positive nor negative, the number is equal to 0. Let's implement the above logic in a Java program using the if-else statement.

What is the difference between negative and zero?

If a number is less than zero, it is a negative number. If a number equals to zero, it is zero. Did you find this article helpful? Sorry about that. How can we improve it?

How do you know if a number is positive or negative?

1 If number>0 the number is positive. 2 If number<0 the number is negative. 3 If a number is neither positive nor negative, the number is equal to 0.

How to convert every negative number to 0?

Recommended: Please try your approach on {IDE} first, before moving on to the solution. The signed shift n>>31 converts every negative number into -1 and every other into 0.


1 Answers

Your problem is that you are using y = -0 instead of y = -0.0. 0 is an integer literal and there is no -0 int value, it just stays 0 and then is widened to +0.0d.You could also use -(double)0 to do the widening before the negation and get the same result as -0.0.

like image 191
Alex - GlassEditor.com Avatar answered Sep 27 '22 22:09

Alex - GlassEditor.com