How do I check if a zero is positive or negative?
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)
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);
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");
}