-6

I have some dimensions typed as a text in inches format, example: text = "20 7/8 16 1/4" # the first two represent, let's say, the length, and the second two represent the width I can change this string into a list of strings using text.split() to get: ["20", "7/8", "16", "1/4"].

Now, I want to add the first two items 20 + 7/8 to get 20.875. How can I convert 7/8 to a float number?

O. Mohsen
  • 179
  • 1
  • 6

5 Answers5

5

A quick Google search can show you the answer

from fractions import Fraction
print float(Fraction('7/8'))
Sevy
  • 688
  • 4
  • 11
1
>>> from __future__ import division
... 
... result = []
... text = "20 7/8 16 1/4"
... for num in text.split():
...     try:
...         numerator, denominator = (int(a) for a in num.split('/'))
...         result.append(numerator / denominator)
...     except ValueError:
...         result.append(int(num))
... 
>>> result
[20, 0.875, 16, 0.25]
G_M
  • 3,342
  • 1
  • 9
  • 23
  • 1
    Don't need `from __future__ import division` for python3 – pault Feb 22 '18 at 23:06
  • @pault You are correct. I just have a Python 2.7 project open in PyCharm so that is what console I'm currently using. Sometimes I also like using `operator.truediv` for Python 2/3 compatibility since it's very obvious. – G_M Feb 22 '18 at 23:09
1
text = "7/8"
x = text.find("/")
numerator = float(text[0:x])
denominator = float(text[x+1:])
print(numerator/denominator)
O. Mohsen
  • 179
  • 1
  • 6
  • 1
    Your answer was flagged as low quality because it lacks explanation. Expand upon why your answer works, or it will be deleted. – Derek Brown Feb 23 '18 at 05:39
  • The code is self-explaining .. take the number to the left of " / ", convert it to a float, take the number to the right of " / ", convert it to a float; then perform a normal division !! – O. Mohsen Sep 26 '18 at 18:52
0

How can I convert 7/8 to a float number?

a="7/8".split("/")
a=int(a[0])/int(a[1])

Or if you don't care about safety:

a=eval("7/8")
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
0
num = '7/8'.split('/')
dec = int(num[0]) / int(num[1])
MalloyDelacroix
  • 2,193
  • 1
  • 13
  • 17