I'm using some function and it requires float number to do some maths. When I try to convert a fraction (example: 3/4 or 6/4) I get
ValueError: could not convert string to float: '3/4'
How can I overcome this problem? Obviously float("3/4")
doesn't really work out great. Thanks in advance
Asked
Active
Viewed 111 times
1

Robin De Schepper
- 4,942
- 4
- 35
- 56

Yolinco
- 13
- 3
-
1Does this answer your question? [Safely evaluate simple string equation](https://stackoverflow.com/questions/43836866/safely-evaluate-simple-string-equation) – Random Davis Mar 11 '21 at 17:46
-
Can you please explain what exactly you are trying to do in details? Maybe there must be some other ways of solving the problem. – Tsubasa Mar 11 '21 at 17:47
-
You could use the fractions module: `from fractions import Fraction` then `float(Fraction('3/4'))` – user3697625 Mar 11 '21 at 17:49
-
I'm trying to make a discord bot @Xua. But franctions module seems the best way so I'd call this subject closed. Thanks everyone – Yolinco Mar 11 '21 at 17:56
3 Answers
1
Using the fractions module (@user3697625)
from fractions import Fraction
string = "3/4"
floatfromstring = float(Fraction(string))

101donutman
- 82
- 9
0
Try this:
string = "3/4"
a = string.split("/")
out = float(a[0]) / float(a[1])
Alternatively, you could use the fractions module:
from fractions import Fraction
out = float(Fraction("3/4"))

QWERTYL
- 1,355
- 1
- 7
- 11