Search code examples
c#.net.net-corefloating-pointfloating-accuracy

Why does .NET Core Convert.ToInt32 round up odd numbers


I have just been reading through some .NET Core code and tried to understand how System.Convert.ToInt32(float n) does its magic.

What irritates me a bit is the decision to round up if the number is odd and >= 0.5.

if (value < 2147483647.5)
{
   int result = (int)value;
   double dif = value - result;
   if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
      return result;
}

What is the reason for the oddity check? A fairly constructed scenario but spead out across an applicationa 1.5 could equal a 2.5.

// True
Convert.ToInt32(1.5) == Convert.ToInt32(2.5)

Solution

  • It's called Round half to even and is one way of rounding numbers in a fair manner. It is also called convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd–even rounding, or bankers' rounding.

    Round half to even: A tie-breaking rule without positive/negative bias and without bias toward/away from zero is round half to even. This function minimizes the expected error when summing over rounded figures, even when the inputs are mostly positive or mostly negative. It is the default rounding mode used in IEEE 754 floating-point operations.

    See: