Rounding in C++

I was recently working on a C++ project that required a floating-point number to be converted to a static integer. Unfortunately, C++ does not offer a rounding function. When the floating-point number was converted to an integer, the decimal value was simply dropped.

C++ does offer floor() and ceil(), but I needed something that would accurately round. So, I wrote a simple function that uses floor():

---------------------------------------------
double round(double x)
{
  return double(floor(x + 0.5));
}
---------------------------------------------

Basically, 0.5 is added to the double variable, x, and then floor() rounds the number down.

If the double number is 3.8, then it will be 4.3 after 0.5 is added to it. 4.3 will equal the whole number 4 after it is rounded by floor().

If the double number is 3.4, then it will be 3.9 after 0.5 is added to it. 3.9 will equal the whole number 3 after it is rounded by floor().

Note that while this function returns a whole number, it is still a double (floating-point).

If you need the double rounded and converted to an integer, use static_cast:

---------------------------------------------
int a;
double x=2.6;

a = static_cast(x+0.5);
---------------------------------------------

In the above example, 0.5 is added to the double x before it is converted to an integer. This works the same way as my original function, but the resulting whole number is an integer instead of a double.