Search code examples
c#.netfloating-point

How can I test for negative zero?


Initially I thought Math.Sign would be the proper way to go but after running a test it seems that it treats -0.0 and +0.0 the same.


Solution

  • Here's a grotty hack way of doing it:

    private static readonly long NegativeZeroBits =
        BitConverter.DoubleToInt64Bits(-0.0);
    
    public static bool IsNegativeZero(double x)
    {
        return BitConverter.DoubleToInt64Bits(x) == NegativeZeroBits;
    }
    

    Basically that's testing for the exact bit pattern of -0.0, but without having to hardcode it.