python 2.7: round a float up to next even number
15,078
Solution 1
There is no need for step 1. Just divide the value by 2, round up to the nearest integer, then multiply by 2 again:
import math
def round_up_to_even(f):
return math.ceil(f / 2.) * 2
Demo:
>>> import math
>>> def round_up_to_even(f):
... return math.ceil(f / 2.) * 2
...
>>> round_up_to_even(1.25)
2
>>> round_up_to_even(3)
4
>>> round_up_to_even(2.25)
4
Solution 2
a = 3.5654
b = 2.568
a = int(a) if ((int(a) % 2) == 0) else int(a) + 1
b = int(b) if ((int(b) % 2) == 0) else int(b) + 1
print a
print b
value of a after execution
a = 4
value of b after execution
b = 2
Author by
Boosted_d16
Python and PowerPoints. The 2 most important Ps in the world.
Updated on June 04, 2022Comments
-
Boosted_d16 almost 2 years
I would like to round up a float to the next even number.
Steps:
1) check if a number is odd or even
2) if odd, round up to next even number
I have step 1 ready, a function which checks if a give number is even or not:
def is_even(num): if int(float(num) * 10) % 2 == 0: return "True" else: return "False"
but I'm struggling with step 2....
Any advice?
Note: all floats will be positive.
-
Donald Duck about 7 yearsWhile this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
-
deweydb about 3 yearsgives
2.0
and4.0
etc. i think this changed in python 3 vs 2 -
Martijn Pieters about 3 years@deweydb yes, you are correct. Python 3 changed the returned type for
math.ceil()
; in Python 2 it returns a float with integral value, in Python 3 an int is returned. -
AleAve81 about 3 yearsI think it is quite obvious why this answer the problem and I like the simplicity of it, upvoted.
-
Mark Dickinson over 2 yearsWhat do you think
round_to_ceil_even(2.3)
should give? Right now, your function simply returns2.3
, which is definitely not an "even number". What about an input of3.3
? (Your function gives4.3
as an output. I doubt that's what the OP wanted.) -
Néstor Waldyd over 2 yearsFunction updated.