9

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.

Axim
  • 332
  • 3
  • 11
  • 1
    "Negative zero" doesn't really make any sense. Zero is neither positive nor negative. – David Oct 08 '16 at 14:55
  • 2
    This may sound like a cop-out, but why not read the input as a `String`, check for `-0`, and if not then parse it as a double? – Tim Biegeleisen Oct 08 '16 at 14:55
  • 2
    Did you already try `Double.doubleToRawLongBits(0.0) == Double.doubleToRawLongBits(-0.0);` as suggested [here](http://stackoverflow.com/a/14771363/205233)? – Filburt Oct 08 '16 at 14:58
  • 4
    @David While that is entirely true in a mathematical sense, it isn't in programming. A floating point zero still has a sign bit which is retained. – Axim Oct 08 '16 at 15:02
  • 3
    @David `-0` does make sense. [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point) defines [signed zero](https://en.wikipedia.org/wiki/Signed_zero) where the sign bit determines whether `+0` or `-0` applies. – Stefan Zobel Oct 08 '16 at 15:03
  • 1
    @Filburt thanks, turns out the problem was me missing the `.0` part – Axim Oct 08 '16 at 15:03
  • 5
    Wouldn’t Double.NaN be an easier sentinel value to check for? – VGR Oct 08 '16 at 15:11
  • @StefanZobel Seconded. – jub0bs Oct 08 '16 at 15:22
  • 2
    @VGR Absolutely, and now I'm questioning my sanity as to why I didn't think of that. – Axim Oct 08 '16 at 15:23

1 Answers1

21

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.

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
Alex - GlassEditor.com
  • 14,957
  • 5
  • 49
  • 49