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

前端 未结 7 1317
孤街浪徒
孤街浪徒 2020-12-01 06:50

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 a

7条回答
  •  無奈伤痛
    2020-12-01 07:34

    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
    }
    

提交回复
热议问题