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?
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.
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.
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.
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
Maybe
rounded_val = len(src_string) & ~1
This simply clears the 1s bit, which is exactly what you need. Only works for int
s, but len should always be integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With