round() for float in C++

Roddy picture Roddy · Jan 27, 2009 · Viewed 384k times · Source

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??

Answer

Andreas Magnusson picture Andreas Magnusson · Jan 27, 2009

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.