Jonathan Mee
Jonathan Mee

Reputation: 38919

Rounding a Positive or Negative Number

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

Answers (3)

marom
marom

Reputation: 5230

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

Upvotes: 8

Glenn Teitelbaum
Glenn Teitelbaum

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

HarryQuake
HarryQuake

Reputation: 163

In C math library, there is,

double round  (double x);

or there is,

double nearbyint  (double x);

Upvotes: 1

Related Questions