Possible Duplicate:
round() for float in C++
In cmath there is floor and ceiling, but I cannot find round. How does one round with the standard library without writing a function and dragging it around into all projects?
Thanks
Possible Duplicate:
round() for float in C++
In cmath there is floor and ceiling, but I cannot find round. How does one round with the standard library without writing a function and dragging it around into all projects?
Thanks
std::floor(x + 0.5)
or std::ceil(x - 0.5)
, depending on how you want to handle the half-integer case.
They are overloaded functions, so if you want to wrap them, you do:
template <typename T>
T round(T x)
{
return std::floor((T)0.5 + x);
}
Don't listen to what people say in the commentaries, floor(-1.6 + 0.5) = floor(-1.1) = -2 as expected.
If you are in C++ you need to write you own round()
template < typename T > T round(const T &x) { return static_cast<int>(x+0.5-(x<0)); }
The same goes for C89. C99 already includes round function in math.h
Edit: as catched by Alexander, floor returns -2 for -1.x, sorry for the mistake (its not as flexible as it was now)