Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 2.7: round a float up to next even number

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.

like image 909
Boosted_d16 Avatar asked Aug 18 '14 11:08

Boosted_d16


2 Answers

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
like image 64
Martijn Pieters Avatar answered Sep 29 '22 09:09

Martijn Pieters


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
like image 27
Sanober Sayyed Avatar answered Sep 29 '22 11:09

Sanober Sayyed