iroundf
A few minutes ago I wrote a rounding function for myself in C. Probably not the best implementation, but it works all right. If you’re interested, check it out (I’ve put some sample values in the comments):
int iroundf(float value)
{
if(value > 0.0)
{
int unsigned cutvalue = (unsigned int)value; // 3.8234234 => 3
float remain = value - cutvalue; // 3.8234234-3 = 0.8234234
if(remain >= 0.5) // 0.8234234 >= 0.5 => TRUE
return cutvalue + 1; // iroundf(3.8234234) => 4
else
return cutvalue;
}
if(value < 0.0)
{
int cutvalue = (int)value; // -1.34 => -1 // -4.67 => -4
float remain = value - cutvalue; // -1.34-(-1) = -0.34 // -4.64-(-4) = -0.64
if(remain >= -0.5) // -0.31 >= -0.5 => TRUE // -0.61 >= -0.5 => FALSE
return cutvalue; // iroundf(-1.34) => -1
else
return cutvalue - 1; // iroundf(-4.67) => -5
}
return 0;
}
update: I just came across the following very short and elegant solution (talk about forests and trees…)
int result = (int)(float_number + 0.5);