arrays, even, roundup, odd round down ?

Serge Orlov Serge.Orlov at gmail.com
Wed May 17 07:35:49 EDT 2006


Lance Hoffmeyer wrote:
> 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]




More information about the Python-list mailing list