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.
There is two methods: float_number = float ( decimal_number ) float_number = decimal_number * 1.0.
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.
maybe something like this (2.6+)
from fractions import Fraction float(sum(Fraction(s) for s in '1 2/3'.split()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With