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
If x is negative, round-down is the same as round-away-from-zero, and round-up is the same as round-toward-zero. In any case, if x is an integer, y is just x .
Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up. And if it is followed by 0, 1, 2, 3, 4 round the number down.
If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down. Example: 33 rounded to the nearest ten is 30.
Rules for Rounding Whole Numbers If the digit is 0, 1, 2, 3, or 4, do not change the rounding digit. All digits that are on the righthand side of the requested rounding digit become 0. If the digit is 5, 6, 7, 8, or 9, the rounding digit rounds up by one number.
For C++ there is one: 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With