How can I convert numbers with decimals to fractions in Python?

I would like to print numeric values with decimals in their fraction Form:

0.5 a 1/2
0.75 a 3/4
4.5 a 9/2

Is there any Native library to perform the conversion? How is such a conversion performed?

 4
Author: Eslacuare, 2016-10-29

3 answers

You can use the Class Fraction of the module fractions:

>>> from fractions import Fraction
>>> a = Fraction('0.5')
>>> b = Fraction('0.75')
>>> c = Fraction('4.5')
>>> print(a)
1/2
>>> print(b)
3/4
>>> print(c)
9/2

If you have the numbers saved as real, then you can do the explicit conversion using str and then pass that the Class Fraction.

 7
Author: Pedro Jorge De Los Santos, 2016-10-29 22:06:43

You can make a recursive function that delivers values for the numerator and denominator of the fraction, regardless of whether it is simplified or not. Then you simplify or factor with Euclid's algorithm.

I leave you the code for the algorithm.

def mcd(a,b):
    assert type(a) == int and type(b) == int and a>0 and b>0
    if a%b != 0:
        return mcd(b,a%b)
    else:
        return b

Then you do something like numerador=numerador/mcd(numerador,denominador) and denominador=denominador/mcd(numerador,denominador) and print it as string:

print(str(numerador)+'/'+str(denominador)).
 3
Author: Rudy Garcia, 2016-10-30 12:59:10

Using the Class Fraction of the module fractions does not return the value of the fraction when it has infinite decimal numbers, therefore it is necessary to add .limit_denominator() after using the class.

from fractions import Fraction
a = 2/9
b=Fraction(str(a))
print('Valor de b: ',b)

c=Fraction(str(a)).limit_denominator()
print('Valor de c: ',c)

And as a result:

Valor de b:  1111111111111111/5000000000000000
Valor de c:  2/9
 3
Author: Arn. Rojas, 2019-11-25 17:17:21