Search code examples
pythonstringpython-2.7floating-pointfractions

String that represents float to fraction


Im trying to handle a string like this:

s = '1/2.05'

When I try to parse it into a Fraction:

Fraction(s)

I am obtaining:

ValueError: ("Invalid literal for Fraction: u'1/2.05'", u'occurred at index 3')

I also tried:

Fraction(s.split('/')[0], s.split('/')[1])

But with error too:

TypeError: ('both arguments should be Rational instances', u'occurred at index 3')

How would the correct parsing be?

Thank you all in advance!


Solution

  • The issue lies in the fact that fractions and floats don't mix, and so you cannot typecast a string that hides a float in the fraction directly.

    Do NOT use eval for this though.
    Try to tackle the numerator and denominator separately. (you could use floats but then it is more precise to directly call Fraction on the string, avoiding precision issues.)

    from fractions import Fraction
    s = '1/2.05'
    numerator, denominator =  s.split('/')
    result = Fraction(numerator)/Fraction(denominator)
    print(result)