Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
Emre Avatar asked Aug 25 '09 07:08

Emre


People also ask

What is rounding away from zero?

Rounding away from zeroMidpoint values are rounded to the next number away from zero. For example, 3.75 rounds to 3.8, 3.85 rounds to 3.9, -3.75 rounds to -3.8, and -3.85 rounds to -3.9. This form of rounding is represented by the MidpointRounding. AwayFromZero enumeration member.

Is there a rounding function in C?

The round( ) function in the C programming language provides the integer value that is nearest to the float, the double or long double type argument passed to it. If the decimal number is between “1 and. 5′′, it gives an integer number less than the argument.

How do you round up in C?

In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).

How does C++ rounding work?

The round() function in C++ returns the integral value that is nearest to the argument, with halfway cases rounded away from zero. It is defined in the cmath header file.


1 Answers

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 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-function version:

x = (x < 0) ? floor(x) : ceil(x);
like image 105
Ruben Bartelink Avatar answered Oct 04 '22 02:10

Ruben Bartelink