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.
source
share