Reputation: 38919
I need to do rounding on a number, but I don't know whether that number is negative or positive.
Is there a better way to round foo
that to do this:
static_cast<int>(foo > 0 ? foo + 0.5 : foo - 0.5)
Basically I want this behavior:
3.4 => 3
3.5 => 4
-3.4 => -3
-3.5 => -4
Upvotes: 7
Views: 7963
Reputation: 10333
Going back to old school C tricks that count on bool
converting to 1 if true
and 0 if false
:
static_cast <int>(foo + 0.5 - (foo < 0.0))
You should generally use library functions, but you can performance test against this if it is a critical section
Upvotes: 4
Reputation: 163
In C math library, there is,
double round (double x);
or there is,
double nearbyint (double x);
Upvotes: 1