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.
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
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
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