Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round() for float in C++

I need a simple floating point rounding function, thus:

double round(double);  round(0.1) = 0 round(-0.1) = 0 round(-0.9) = -1 

I can find ceil() and floor() in the math.h - but not round().

Is it present in the standard C++ library under another name, or is it missing??

like image 330
Roddy Avatar asked Jan 27 '09 22:01

Roddy


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.

Can you round floats?

Python has an inbuilt function round(), which will take the float value and round it off. The round() function takes two parameters: Number and Ndigits (optional). Ndigits represent the number of decimal places to round.

Does float round up or down?

Float number always round up.

How do you round a float to two decimal places?

Just use the formatting with %. 2f which gives you round down to 2 decimal points.


1 Answers

Editor's Note: The following answer provides a simplistic solution that contains several implementation flaws (see Shafik Yaghmour's answer for a full explanation). Note that C++11 includes std::round, std::lround, and std::llround as builtins already.

There's no round() in the C++98 standard library. You can write one yourself though. The following is an implementation of round-half-up:

double round(double d) {   return floor(d + 0.5); } 

The probable reason there is no round function in the C++98 standard library is that it can in fact be implemented in different ways. The above is one common way but there are others such as round-to-even, which is less biased and generally better if you're going to do a lot of rounding; it's a bit more complex to implement though.

like image 88
Andreas Magnusson Avatar answered Sep 20 '22 17:09

Andreas Magnusson