How to get a -0 result in floating point calculations and distinguish it from +0 in C#?

前端 未结 5 1689
难免孤独
难免孤独 2021-01-05 17:44

The MSDN documentation mentions that double type includes negative zero. However, both -1.0 / double.PositiveInfinity and -double.Epsilon / 2

5条回答
  •  甜味超标
    2021-01-05 18:37

    One way is to use the BitConverter.GetBytes. If you check the bytes, you will see that the sign bit for the value is actually set indicating that its negative.

    byte[] zeroBytes = BitConverter.GetBytes(zero);
    byte[] negZeroBytes = BitConverter.GetBytes(negZero);
    
    bool sameBytes = zeroBytes[7] == negZeroBytes[7];
    

提交回复
热议问题