arrays, even, roundup, odd round down ?

L

Lance Hoffmeyer

So, I have using the following to grab numbers from MS Word. I discovered that that there is a "special"
rule being used for rounding.

If a ??.5 is even the number is to rounded down (20.5 = 20)
if a ??.5 is odd the number is to rounded up (21.5 = 22)

Brands = ["B1","B2"]
A1 = []
A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, target_table).group(1) for i in Brands ]
A1 = [int(float(str(x))+0.5) for x in A1 ]
print A1


Any solutions for this line with the above conditions?
Just as a note, any other number ??.3,??.7 follows the normal pattern
of rounding (21.3 = 21, 20.3 = 20, 21.7 = 22, 20.7 = 21)

A1 = [int(float(str(x))+0.5) for x in A1 ]

Lance
 
B

Ben Finney

Lance Hoffmeyer said:
So, I have using the following to grab numbers from MS Word. I
discovered that that there is a "special" rule being used for
rounding.

If a ??.5 is even the number is to rounded down (20.5 = 20)
if a ??.5 is odd the number is to rounded up (21.5 = 22)

This sounds specific enough that I'd want it in a separate function.

def specially_rounded_integer(num):
""" Round a number using our special rules """
rounded_num = num * phase_of_moon() # or whatever else you need to do
return rounded_num
Brands = ["B1","B2"]
A1 = []
A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, target_table).group(1) for i in Brands ]
A1 = [int(float(str(x))+0.5) for x in A1 ]
print A1

original_nums = however_you_get_them()
rounded_nums = [specially_rounded_integer(n) for n in original_nums]

If it's not quickly obvious on a single line, express it more
fully. Future readers, including yourself, will thank you.
 
S

Serge Orlov

Lance said:
So, I have using the following to grab numbers from MS Word. I discovered that that there is a "special"
rule being used for rounding.

If a ??.5 is even the number is to rounded down (20.5 = 20)
if a ??.5 is odd the number is to rounded up (21.5 = 22)

Brands = ["B1","B2"]
A1 = []
A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, target_table).group(1) for i in Brands ]
A1 = [int(float(str(x))+0.5) for x in A1 ]
print A1


Any solutions for this line with the above conditions?

Seems like a job for Decimal:

from decimal import Decimal
numbers = "20.50 21.5".split()
ZERO_PLACES = Decimal("1")
print [int(Decimal(num).quantize(ZERO_PLACES)) for num in numbers]

produces

[20, 22]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,835
Latest member
lila30

Latest Threads

Top