6

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

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288

3 Answers3

8

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

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
marom
  • 5,064
  • 10
  • 14
  • 1
    I know this extends the question but is there any way to do this pre-c++11? – Jonathan Mee Jul 01 '15 at 14:16
  • 1
    I'm accepting this answer, however I'd like to note that [Glenn Teitebaum's answer](http://stackoverflow.com/a/31163962/2642059) is a good solution if you do not have access to C++11 or more simply just do `static_cast(foo + 0.5 - (foo < 0.0))`. – Jonathan Mee Jul 02 '15 at 10:33
4

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

Glenn Teitelbaum
  • 10,108
  • 3
  • 36
  • 80
  • I like the idea of using a condition, but not branching on it. But I think we can do better than your solution: http://stackoverflow.com/questions/31162992/rounding-a-positive-or-negative-number#comment50369982_31163049 – Jonathan Mee Jul 02 '15 at 10:34
  • @JonathanMee Mind if i update the solution to show your simplified math? – Glenn Teitelbaum Jul 02 '15 at 11:07
  • 1
    Nope, sounds great. It would be good to have the simplified math as a solution. – Jonathan Mee Jul 02 '15 at 11:11
1

In C math library, there is,

double round  (double x);

or there is,

double nearbyint  (double x);
HarryQuake
  • 163
  • 1
  • 13