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
}