Question

Is it possible to check if a float is a positive zero (0.0) or a negative zero (-0.0)?

I've converted the float to a String and checked if the first char is a '-', but are there any other ways?

Was it helpful?

Solution

Yes, divide by it. 1 / +0.0f is +Infinity, but 1 / -0.0f is -Infinity. It's easy to find out which one it is with a simple comparison, so you get:

if (1 / x > 0)
    // +0 here
else
    // -0 here

(this assumes that x can only be one of the two zeroes)

OTHER TIPS

You can use Float.floatToIntBits to convert it to an int and look at the bit pattern:

float f = -0.0f;

if (Float.floatToIntBits(f) == 0x80000000) {
    System.out.println("Negative zero");
}

Definitly not the best aproach. Checkout the function

Float.floatToRawIntBits(f);

Doku:

/**
 * Returns a representation of the specified floating-point value
 * according to the IEEE 754 floating-point "single format" bit
 * layout, preserving Not-a-Number (NaN) values.
 *
 * <p>Bit 31 (the bit that is selected by the mask
 * {@code 0x80000000}) represents the sign of the floating-point
 * number.
 ...
 public static native int floatToRawIntBits(float value);

Double.equals distinguishes ±0.0 in Java. (There's also Float.equals.)

I'm a bit surprised no-one has mentioned these, as they seem to me clearer than any method given so far!

The approach used by Math.min is similar to what Jesper proposes but a little clearer:

private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);

float f = -0.0f;
boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);

When a float is negative (including -0.0 and -inf), it uses the same sign bit as a negative int. This means you can compare the integer representation to 0, eliminating the need to know or compute the integer representation of -0.0:

if(f == 0.0) {
  if(Float.floatToIntBits(f) < 0) {
    //negative zero
  } else {
    //positive zero
  }
}

That has an extra branch over the accepted answer, but I think it's more readable without a hex constant.

If your goal is just to treat -0 as a negative number, you could leave out the outer if statement:

if(Float.floatToIntBits(f) < 0) {
  //any negative float, including -0.0 and -inf
} else {
  //any non-negative float, including +0.0, +inf, and NaN
}

For negative:

new Double(-0.0).equals(new Double(value));

For positive:

new Double(0.0).equals(new Double(value));

Just use Double.compare (d1,d2).

double d1 = -0.0;    // or d1 = 0.0

if ( Double.compare (d1, 0.0)  < 0 )
    System.out.println("negative zero");
else
    System.out.println("positive zero");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top