I want to write a function to round a double to an int using Banker's Rounding method (round half to even: http://en.wikipedia.org/wiki/Rounding#Round_half_to_even), like:
int RoundToInt(double x);
How can I do that?
Update:
The best I can get is this:
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 this is slow and I'm not even sure if it is accurate.
Is there some quick and accurate way to do this.