c++doublerounding

c++ rounding of numbers away from zero


Hi i want to round double numbers like this (away from zero) in C++:

  4.2 ---->   5
  5.7 ---->   6
 -7.8 ---->  -8
-34.2 ----> -35

What is the efficient way to do this?


Solution

  • inline double myround(double x)
    {
      return x < 0 ? floor(x) : ceil(x);
    }
    

    As mentioned in the article Huppie cites, this is best expressed as a template that works across all float types. (See floor and ceil for a detailed reference.)

    As suggested by Pax, a non-function version can be as effective (sometimes more efficient):

    x = (x < 0) ? floor(x) : ceil(x);