Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 618
Jonathan Mee Avatar asked Jul 01 '15 13:07

Jonathan Mee


People also ask

Do you round negative numbers?

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 .

What is the rule of rounding a number?

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.

What are the 4 rules of rounding?

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.

When should you not round numbers?

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.


2 Answers

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

like image 167
marom Avatar answered Sep 22 '22 02:09

marom


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

like image 44
Glenn Teitelbaum Avatar answered Sep 22 '22 02:09

Glenn Teitelbaum