Round a positive or negative number

I need to do rounding on a number, but I don't know if the number is negative or positive.

Is there a better way to round up foo

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

+3


source to share


3 answers


For C ++ there is one: std::lround



+8


source


Going back to the old school 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 normally use library functions, but you can perform a performance test against this if this is a critical section

+2


source


The C-math library has,

double round  (double x);

      

or exists,

double nearbyint  (double x);

      

+1


source







All Articles