Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert fraction to float?

Tags:

python

parsing

Kind of like this question, but in reverse.

Given a string like 1, 1/2, or 1 2/3, what's the best way to convert it into a float? I'm thinking about using regexes on a case-by-case basis, but perhaps someone knows of a better way, or a pre-existing solution. I was hoping I could just use eval, but I think the 3rd case prevents that.

like image 552
mpen Avatar asked Nov 27 '09 00:11

mpen


People also ask

How do you convert a decimal to a float in Python?

There is two methods: float_number = float ( decimal_number ) float_number = decimal_number * 1.0.

How do you convert a string to a fraction in Python?

We can also convert a string to fraction using the Fraction() method. We can pass a string representation of fraction or a floating point literal in the string as input to the Fraction method which returns the corresponding fraction values as follows.


1 Answers

maybe something like this (2.6+)

from fractions import Fraction float(sum(Fraction(s) for s in '1 2/3'.split())) 
like image 161
newacct Avatar answered Sep 19 '22 22:09

newacct