round() for float in C++

Editor’s Note: The following answer provides a simplistic solution that contains several implementation flaws (see Shafik Yaghmour’s answer for a full explanation). Note that C++11 includes std::round, std::lround, and std::llround as builtins already.

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.

Leave a Comment