Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 503
Luiz Berti Avatar asked Mar 03 '14 18:03

Luiz Berti


People also ask

How do you round off odd and even numbers?

Odds and evens rule EVEN: If the last retained digit is even, its value is not changed, the 5 and any zeros that follow are dropped. ODD: if the last digit is odd, its value is increased by one.

How do you round an odd number?

This familiar rule is used by many rounding methods. If the difference between the number and the nearest integer is exactly 0.5, look at the integer part of the number. If the integer part is EVEN, round towards zero. If the integer part of the number is ODD, round away from zero.

What is the 5 rounding rule?

In rounding off numbers, if the first figure dropped is 5, and all the figures following the five are zero or if there are no figures after the 5, then the last figure kept should be unchanged if that last figure is even. For example, if only one decimal is to be kept, then 6.6500 becomes 6.6.


2 Answers

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

rounded_val = (len(src_string) // 2) * 2
like image 164
Martijn Pieters Avatar answered Nov 15 '22 07:11

Martijn Pieters


Maybe

rounded_val = len(src_string) & ~1

This simply clears the 1s bit, which is exactly what you need. Only works for ints, but len should always be integer.

like image 37
AShelly Avatar answered Nov 15 '22 09:11

AShelly