## #1,092 – Positive and Negative Zero

May 8, 2014 Leave a comment

Because .NET uses the IEEE 754 standard to represent floating point numbers, it allows representing both positive and negative zero values. (+0.0 and -0.0).

Mathematically, +0.0 is equal to -0.0 and an equality check in C# will return a **true** result. However, although the values are considered equal, either value can be represented in C# and they are stored differently in memory.

float zero = 0.0f; float negZero = -0.0f; bool theyAreEqual = zero == negZero; // true // 00-00-00-00 Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(zero))); // 00-00-00-80 Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(negZero))); float sum1 = zero + 1.0f; float sum2 = negZero + 1.0f; bool sumsEqual = sum1 == sum2; // true

You can think of a floating point representation of zero as being either zero or a very small positive number that rounds to zero when stored as a floating point. If the value was a tiny bit above zero before rounding, it’s stored as +0.0. If it was a bit below zero before rounding, it’s stored as -0.0.