Python 2.7: combine a float to the next even number

I would like to round the float to the next even number.

Steps:

1) check if the number is odd or even

2) if odd, rounded to the next even number

I have ready step 1, a function that checks if the number of pressures is even or not:

def is_even(num): if int(float(num) * 10) % 2 == 0: return "True" else: return "False" 

but I'm afraid with step 2 ....

Any tips?

Note: all floats will be positive.

+6
source share
2 answers

There is no need for step 1. Just divide the value by 2, round 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 
+14
source
 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 

a value after execution

 a = 4 

b value after execution

 b = 2 
0
source

Source: https://habr.com/ru/post/973971/


All Articles