Scott
Scott

Reputation: 11

Python: indexing floats?

I have two sets of data that I am reading via nested for loops in Python. I need to match lines of the two different text files using a common number (time). In the two files, time is written differently (ex. 21:53:28.339 vs. 121082008.3399). I only need the last four digits of the times to match them up, for example from 21:53:28.339, I only need '8.339'. For the most part, indexing the number as a string works just fine (ex: timeList[nid][7:]), except for situations such as the numbers listed above, where python rounds .3399 to .34.

Is there a way for me to keep the numbers in float form and to select unrounded digits from the data?

Thanks!

Upvotes: 1

Views: 2005

Answers (3)

John Machin
John Machin

Reputation: 83002

It appears from your description that you want to compare using one digit before the decimal point and 3 digits after the decimal point, using truncation instead of rounding. So just do that:

>>> def extract(s):
...     i = s.find('.')
...     return s[i-1:i+4]
...
>>> map(extract, ['21:53:28.339', '121082008.3399'])
['8.339', '8.339']
>>>

Upvotes: 1

Henry
Henry

Reputation: 6620

edit - using Decimal exclusively - with full example

import decimal

def simplify(text):
    # might be a : separated value
    text = text.split(':')[-1]
    # turn into decimal
    number = decimal.Decimal(text)
    # remove everything but the ones place and forwards
    number = number - (number/10).quantize(1, rounding=decimal.ROUND_FLOOR) * 10
    # truncate to the thousandths
    return number.quantize(decimal.Decimal('.001'), rounding=decimal.ROUND_FLOOR)

a = '121082008.3399'
b = '21:53:28.339'

assert simplify(a) == simplify(b)
print simplify(a), '=', simplify(b)

Scott if you compare the numbers using strings then you don't need any floats and there will be no 'rounding' going on.

'8.339' == '8.339'

or, if you have

a = '8.3399'
b = '8.339'

then

a[:-1] == b

however if you do decide to work with them as 'numbers', then as Ignacio pointed out, you can use decimals.

from decimal import Decimal
number_a = Decimal(a[:-1])
number_b = Decimal(b)

now

number_a == number_b

Hope that helps

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799160

Use decimal.Decimal instead of float.

Upvotes: 0

Related Questions