Rounding a number to nearest even

Graham Breed x31equsenet at gmail.com
Fri Apr 11 10:50:33 EDT 2008


On Apr 11, 6: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

If you care about such details, you may be better off using decimals
instead of floats.

> 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 ?

import decimal
decimal.Decimal("1.5").to_integral(
    rounding=decimal.ROUND_HALF_EVEN)
decimal.Decimal("2.5").to_integral(
    rounding=decimal.ROUND_HALF_EVEN)

ROUND_HALF_EVEN is the default, but maybe that can be changed, so
explicit is safest.

If you really insist,

import decimal
def my_round(f):
    d = decimal.Decimal(str(f))
    rounded = d.to_integral(rounding=decimal.ROUND_HALF_EVEN)
    return int(rounded)


                Graham



More information about the Python-list mailing list