简体   繁体   中英

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

对于C ++,有一个: std::lround

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

In C math library, there is,

double round  (double x);

or there is,

double nearbyint  (double x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM