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开发者_StackOverflow. Here's what I'm looking for, btw:
convert(1 1/2)
or
convert('1 1/2')
Thanks.
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)
I wrote the Mixed
class to extend fractions to do just that. Source is here.
>>> float(Mixed('6 7/8'))
6.875
>>> float(Mixed(1,1,2)) # 1 1/2
1.5
精彩评论