What is the best way to round an odd number to one?

I was rewriting some old code when I came across the following:

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

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

What is the best way to do this?

+6
source share
5 answers

How about this:

 rounded_val = len(src_string) & (-2) 

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

+4
source

Use // floor division instead if you don't like relying on Python 2 / behavior for integer operands:

 rounded_val = (len(src_string) // 2) * 2 
+19
source

maybe

 rounded_val = len(src_string) & ~1 

It just clears bit 1s, which is exactly what you need. Only works for int s, but len ​​should always be integer.

+10
source

The // operator is probably the best choice, but you can also use the divmod function:

 rounded_val = divmod(len(src_string), 2)[0] * 2 
+2
source

Why not this:

 rounded_val = len(src_string) - len(src_string) % 2 
+1
source

All Articles