round() for float in C++

Question

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 `ceil()` and `floor()` in the math.h - but not `round()`.

Is it present in the standard C++ library under another name, or is it missing??

1
226
3/16/2017 1:55:02 AM

There's no round() in the C++98 standard library. You can write one yourself though. The following is an implementation of round-half-up:

``````double round(double d)
{
return floor(d + 0.5);
}
``````

The probable reason there is no round function in the C++98 standard library is that it can in fact be implemented in different ways. The above is one common way but there are others such as round-to-even, which is less biased and generally better if you're going to do a lot of rounding; it's a bit more complex to implement though.

139
9/27/2017 9:16:53 AM

Boost offers a simple set of rounding functions.

``````#include <boost/math/special_functions/round.hpp>

double a = boost::math::round(1.5); // Yields 2.0
int b = boost::math::iround(1.5); // Yields 2 as an integer
``````

Edit: Since C++11, there are `std::round`, `std::lround`, and `std::llround`.