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

前端 未结 7 1315
孤街浪徒
孤街浪徒 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

    Double.equals distinguishes ±0.0 in Java. (There's also Float.equals.)

    I'm a bit surprised no-one has mentioned these, as they seem to me clearer than any method given so far!

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-01 07:39

    The approach used by Math.min is similar to what Jesper proposes but a little clearer:

    private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);
    
    float f = -0.0f;
    boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);
    
    0 讨论(0)
  • 2020-12-01 07:43

    For negative:

    new Double(-0.0).equals(new Double(value));
    

    For positive:

    new Double(0.0).equals(new Double(value));
    
    0 讨论(0)
  • 2020-12-01 07:49

    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);
    
    0 讨论(0)
  • 2020-12-01 07:52

    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");
    }
    
    0 讨论(0)
提交回复
热议问题