0

I'm attempting to get a user input as a fraction but use it as a decimal, in python

For example:

chance = input("Enter chance")

Let's assume the user enters "3/4"

How can I convert "3/4" to "0.75" for further calculations, such as:

total = chance + 36/67  # Where total is a float value

P.S. I'm new to python so if this seems a bad question I apologise but I couldnt find an answer anywhere.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

2

Lets assume you've handled getting the user to input text. Then convert that text to a fractions.Fraction

>>> import fractions
>>> fractions.Fraction("3/4")
Fraction(3, 4)

You have various options from there. You could continue to use it as a Fraction but if you insist on using values of type float then simply convert to a float

>>> float(fractions.Fraction("3/4"))
0.75
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
-1

Check the input format and convert to numerator/denominator as needed before performing the necessary math operation to convert it from a fraction to a decimal value.

chance = "3/4"

# verify that format is valid, then proceed to conversion
tokens = chance.split("/")
numer = int(tokens[0])
denom = int(tokens[1])
value = numer / denom
print(value)

If you're using an older version of python (eg 2.x) you will need to convert one of the parts to a float because python discards floating point during int/int division.

MxLDevs
  • 19,048
  • 36
  • 123
  • 194