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.
It can also handle "2 1/1e-8", "-1/3" and "1/5e3".
That might be a dirty workaround, but you could convert spaces to a
+
sign to solve the 3rd case (or to a-
if your fraction is negative).Though you should stear clear of eval completely. Perhaps some more refined version of:
Sorry, meant to be num.split not s.split, and casts. Edited.