Search code examples
javafloating-pointzero

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?


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)