Axim - 10 months ago 62

Java Question

I've been trying to figure out how to determine if a double value is

`-0.0d`

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`

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.

Answer Source

Your problem is that you are using `y = -0`

instead of `y = -0.0`

. `0`

is and 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`

.