I need a simple floating point rounding function, thus:
double round(double);
round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1
I can find
Function double round(double)
with the use of the modf
function:
double round(double x)
{
using namespace std;
if ((numeric_limits::max() - 0.5) <= x)
return numeric_limits::max();
if ((-1*std::numeric_limits::max() + 0.5) > x)
return (-1*std::numeric_limits::max());
double intpart;
double fractpart = modf(x, &intpart);
if (fractpart >= 0.5)
return (intpart + 1);
else if (fractpart >= -0.5)
return intpart;
else
return (intpart - 1);
}
To be compile clean, includes "math.h" and "limits" are necessary. The function works according to a following rounding schema: