python 2.7: round a float up to next even number

╄→гoц情女王★ 提交于 2020-01-24 02:25:07

问题


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.


回答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



回答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


来源:https://stackoverflow.com/questions/25361757/python-2-7-round-a-float-up-to-next-even-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!