C ++ rounding numbers 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 an effective way to do this?

+6
c ++ double rounding
source share
3 answers
 inline double myround(double x) { return x < 0 ? floor(x) : ceil(x); } 

As mentioned in a Huppie article cites , this is best expressed as a template that works in all float types

See http://en.cppreference.com/w/cpp/numeric/math/floor and http://en.cppreference.com/w/cpp/numeric/math/floor

or, thanks to Pax, a non-functional version:

 x = (x < 0) ? floor(x) : ceil(x); 
+25
source share

There is a good article on a similar issue on CPlusPlus.com . An easy solution to your problem should be something like this:

 double customRound( double value ) const { return value < 0 ? floor( value ) : ceil( value ); } 

The best solution is the one mentioned in the article that uses the template:

 //-------------------------------------------------------------------------- // symmetric round up // Bias: away from zero template <typename FloatType> FloatType ceil0( const FloatType& value ) { FloatType result = std::ceil( std::fabs( value ) ); return (value < 0.0) ? -result : result; } 
+2
source share

to try

  double rounded = _copysign(ceil(abs(x)), x); 
-one
source share

All Articles