Lothar the Quick
Lothar the Quick

Reputation: 89

Python Convert Fraction Inside String to Integer

How can I convert an input entered as a fraction (eg, "4/2") into an integer in python 3.5? I have tried using both of the following codes:

b = int(input("Please enter a value for b of the quadratic equation: "))
b = int(float(input("Please enter a value for b of the quadratic equation: ")))

Upvotes: 3

Views: 8111

Answers (2)

Matt Hall
Matt Hall

Reputation: 8142

Use fractions.

>>> from fractions import Fraction
>>> int(Fraction('4/2'))
2

Whatever you do, don't use eval.

Note that int() always rounds towards zero. Depending on the behaviour you want, you might want to check out round(), math.floor() or math.ceil().

Upvotes: 20

Nicolas B.
Nicolas B.

Reputation: 21

With the standard library for regular expression re, you can test if the fraction is well formatted:

>>> import re
>>> fraction_pattern = re.compile(r"^(?P<num>[0-9]+)/(?P<den>[0-9]+)$")

and then:

>>> g = fraction_pattern.search('355/113')
>>> if g:
        f = float(g.group("num"))/float(g.group("den"))
>>> f
3.1415929203539825

But may not be the fastest nor the simplest solution compared to fractions...

Upvotes: 2

Related Questions