How to round double to int using Banker rounding in C

I want to write a function to round double to int using the Banker rounding method (half to even: http://en.wikipedia.org/wiki/Rounding#Round_half_to_even ) as:

int RoundToInt(double x);

How can i do this?

Update

The best I can get is:

int RoundToInt(double x)
{
  int s = (int)x;
  double t = fabs(x - s);

  if ((t < 0.5) || (t == 0.5 && s % 2 == 0))
  {
    return s;
  }
  else
  {
    if (x < 0)
    {
      return s - 1;
    }
    else
    {
      return s + 1;
    }
  }
}

But it's slow, and I'm not even sure how accurate it is.

Is there a quick and accurate way to do this.

+5
source share
2 answers

Use a standard function lrint; in default rounding mode, it gives exactly the result you want.

+4
source
double decimal = x % 1;
if(decimal < 0.5) return (int)x;
if(decimal > 0.5) return (int)x + 1;
return (int)x + ((int)x % 2 == 1 ? 1 : 0);
+1
source

All Articles