tags:

views:

2576

answers:

4

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?

+12  A: 

That's right there is no round() function, but there is floor(), which always rounds to the lower number, and 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.

Patrick Daryll Glandien
You think it's *cleaner* to convert to a string and back?
Paul Tomblin
Yes, using the +0.5-technique you will encounter problems with negative numbers and you also don't have control over the precision.
Patrick Daryll Glandien
+0.5 should work fine as long as you use floor(). Anyway, then it becomes a question of correctness, and not which is cleaner.
jalf
what problems are there with negative numbers? if you don't need control precision then the stringstream solution is way slower for no reason. maybe a template-specialization would make sense here, if you really want to give precision control.
wilhelmtell
also, i should remind you that 0.5 is represented as an exact number.
wilhelmtell
A: 

There actually isn't a round function in Microsoft math.h.
However you could use the static method Math::Round() instead.
(Depending on your project type.)

Sani Huttunen
+1  A: 

I don't know if it's best practice or not but using the 0.5 technique with a floor() seems to be the way to go.

Elroy
+5  A: 

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);
}
Bill the Lizard
It's worth mentioning that I had written this with if...else until I saw litb's more concise version on the duplicate. http://stackoverflow.com/questions/485525/round-for-float-in-c/485549#485549
Bill the Lizard