Search code examples
pythonmathintegerroundinglegacy

Whats the best way to round an odd number to an even one?


I was rewritting some legacy code, when I stumbled into the following:

rounded_val = (len(src_string) / 2) * 2

This takes advantage of integer division behavior, to round the length value of the string, if odd, to the first even value before it. But integer division is about to change on Python 3, and I need to change this line.

What is the optimal way to do this?


Solution

  • How about this:

    rounded_val = len(src_string) & (-2)
    

    Although it is sometimes not obvious to someone not familiar with binary arithmetic.