Rounding a number to nearest even
Ivan Illarionov
ivan.illarionov at gmail.com
Fri Apr 11 08:58:46 EDT 2008
On Apr 11, 2:14 pm, bdsatish <bdsat... at gmail.com> wrote:
> The built-in function round( ) will always "round up", that is 1.5 is
> rounded to 2.0 and 2.5 is rounded to 3.0.
>
> If I want to round to the nearest even, that is
>
> my_round(1.5) = 2 # As expected
> my_round(2.5) = 2 # Not 3, which is an odd num
>
> I'm interested in rounding numbers of the form "x.5" depending upon
> whether x is odd or even. Any idea about how to implement it ?
def even_round(x):
if x % 1 == .5 and not (int(x) % 2):
return float(int(x))
else:
return round(x)
nums = [ 3.2, 3.6, 3.5, 2.5, -.5, -1.5, -1.3, -1.8, -2.5 ]
for num in nums:
print num, '->', even_round(num)
3.2 -> 3.0
3.6 -> 4.0
3.5 -> 4.0
2.5 -> 2.0
-0.5 -> 0.0
-1.5 -> -2.0
-1.3 -> -1.0
-1.8 -> -2.0
-2.5 -> -2.0
More information about the Python-list
mailing list