How to get a fraction from a decimal number in Python
Overview
Given that there’s a decimal value, we will learn to obtain the fraction that represents the exact value of the decimal value.
Example
The decimal number -5.422 must be represented in the fractional form as -6104629294900707 / 1125899906842624 where -6104629294900707 is the numerator and 1125899906842624 is the denominator.
The Decimal class
The Decimal class represents decimals in Python. The as_integer_ratio() method of the Decimal class gets a pair, i.e., (numerator, denominator) of integers. These integers represent the given Decimal instance as a fraction in the lowest terms and with a positive denominator.
Syntax
as_integer_ratio()
Code
import decimaldecimal_value = -5.422decimal_object = decimal.Decimal(decimal_value)numerator, denominator = decimal_object.as_integer_ratio()print("%s / %s = %s" % (numerator, denominator, decimal_value))
Code explanation
- Line 1: We import the
decimalmodule. - Line 3: We define a decimal value called
decimal_value. - Line 5: We obtain an instance of the
Decimalclass calleddecimal_objectfordecimal_value. - Line 7: We get the numerator and the denominator using the
as_integer_ratio()method. - Line 9: We print the numerator and denominator.
The Fractions class
The Fractions class represents fractions in Python. The from_decimal() method of the Fractions class gets an instance of the Fractions class from the Decimal object.
- We get a
Decimalobject for the given decimal value. - We use the
from_decimal()method to get an instance of theFractionsclass. - We use the as_integer_ratio() method of the
Fractionsclass to get the numerator and the denominator.
Code
import fractions, decimaldecimal_value = -5.422decimal_object = decimal.Decimal(decimal_value)fraction_object = fractions.Fraction.from_decimal(decimal_object)numerator, denominator = fraction_object.as_integer_ratio()print("%s / %s = %s" % (numerator, denominator, decimal_value))
Code explanation
- Line 1: We import the
decimaland thefractionsmodule. - Line 3: We define a decimal value called
decimal_value. - Line 5: We obtain an instance of the
Decimalclass calleddecimal_objectfor thedecimal_value. - Line 7: We create an instance of the
Fractionsclass calledfraction_objectusing thefrom_decimalmethod, passingdecimal_objectas argument. - Line 9: We get the numerator and the denominator by invoking the
as_integer_ratio()onfraction_object. - Line 11: We print the numerator and denominator.