floating point - python 2.7: round a float up to next even number -
i round float next number.
steps:
1) check if number odd or even
2) if odd, round next number
i have step 1 ready, function checks if give number or not:
def is_even(num): if int(float(num) * 10) % 2 == 0: return "true" else: return "false"
but i'm struggling step 2....
any advice?
note: floats positive.
there no need step 1. divide value 2, round nearest integer, multiply 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
Comments
Post a Comment