Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is Round() in C++? [duplicate]

Tags:

c++

rounding

Duplicate of: round() for float in C++


I'm using VS2008 and I've included math.h but I still can't find a round function. Does it exist?

I'm seeing a bunch of "add 0.5 and cast to int" solutions on google. Is that the best practice?

like image 275
Jason Punyon Avatar asked Feb 16 '09 19:02

Jason Punyon


People also ask

How does round () work 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.

Do floats round in C?

There is a round() function, also fround() , which will round to the nearest integer expressed as a double.

How do you round down a double in C++?

round() in C++. The round() function in C++ is used to round off the double, float or long double value passed to it as a parameter to the nearest integral value. The header file used to use the round() function in a c++ program is <cmath> or <tgmath>.


2 Answers

You may use C++11's std::round().

If you are still stuck with older standards, you may use std::floor(), which always rounds to the lower number, and std::ceil(), which always rounds to the higher number.

To get the normal rounding behaviour, you would indeed use floor(i + 0.5).

This way will give you problems with negative numbers, a workaround for that problem is by using ceil() for negative numbers:

double round(double number) {     return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5); }

Another, cleaner, but more resource-intensive, way is to make use of a stringstream and the input-/output-manipulators:

#include <iostream> #include <sstream>  double round(double val, int precision) {     std::stringstream s;     s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;     s >> val;     return val; }

Only use the second approach if you are not low on resources and/or need to have control over the precision.

like image 140
Patrick Glandien Avatar answered Sep 29 '22 15:09

Patrick Glandien


Using floor(num + 0.5) won't work for negative numbers. In that case you need to use ceil(num - 0.5).

double roundToNearest(double num) {     return (num > 0.0) ? floor(num + 0.5) : ceil(num - 0.5); } 
like image 27
Bill the Lizard Avatar answered Sep 29 '22 16:09

Bill the Lizard