For those who doesn't want to use import.
For a given list or any number:
x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999]
You must first evaluate if the number is equal to its integer, which always rounds down. If the result is True, you return the number, if is not, return the integer(number) + 1.
w = lambda x: x if x == int(x) else int(x)+1
[w(i) for i in z]
>>> [2, 3, 3, 3, 4, 4, 3, 3, 4, 4]
Math logic:
- If the number has decimal part: round_up - round_down == 1, always.
- If the number doens't have decimal part: round_up - round_down == 0.
So:
- round_up == x + round_down
With:
- x == 1 if number != round_down
- x == 0 if number == round_down
You are cutting the number in 2 parts, the integer and decimal. If decimal isn't 0, you add 1.
PS:I explained this in details since some comments above asked for that and I'm still noob here, so I can't comment.
round(number + .5)
doesn't work if the number is integer.round(3+.5) == 4
, when you actually want3
. – Ellaelladine