Is there a Python module where I could easily convert mixed fractions to float?

I'm just wondering if I can easily convert a mixed number (entered as a number or a string) to a floating point number or an integer. I looked at the fractions module, but it didn't seem to be able to do what I want, or I read poorly.

Just wanted to know if something already exists before I write my own function. Here is what I'm looking for, by the way:

convert(1 1/2)

or

convert('1 1/2')

Thank.

+5
source share
2 answers

The built-in class Fractiondoesn't seem to support mixed fractions like yours, but it would not be too difficult to split them into space. For example, 1 + fractions.Fraction('1/2')or very simplified

def convert(f):
    whole, frac = f.split()
    return int(whole) + fractions.Fraction(frac)
+9

Mixed , . .

>>> float(Mixed('6 7/8'))
6.875
>>> float(Mixed(1,1,2)) # 1 1/2
1.5
0

All Articles