How do I check if a zero is positive or negative?

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?


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)


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);