Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm just wondering if I could easily convert a mixed number (entered as a number or a string) into a floating point number or an integer. I've looked at the fractions module but it seems like it couldn't do what I want, or I didn't read well.

Just wanted to know if something already exists before I write my own function. Here's what I'm looking for, btw:

convert(1 1/2)

or

convert('1 1/2')

Thanks.

like image 906
arscariosus Avatar asked Sep 11 '11 04:09

arscariosus


1 Answers

The built-in Fraction class does not appear to support mixed fractions like you have, but it wouldn't be too hard to split them up on the space. For example, 1 + fractions.Fraction('1/2') or a very simplistic

def convert(f):
    whole, frac = f.split()
    return int(whole) + fractions.Fraction(frac)
like image 153
Gabe Avatar answered Oct 02 '22 02:10

Gabe