Given that there’s a decimal value, we will learn to obtain the fraction that represents the exact value of the decimal value.
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.
Decimal classThe 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.
as_integer_ratio()
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))
decimal module.decimal_value.Decimal class called decimal_object for decimal_value.as_integer_ratio() method.Fractions classThe 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.
Decimal object for the given decimal value.from_decimal() method to get an instance of the Fractions class.Fractions class to get the numerator and the denominator.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))
decimal and the fractions module.decimal_value.Decimal class called decimal_object for the decimal_value.Fractions class called fraction_object using the from_decimal method, passing decimal_object as argument.as_integer_ratio() on fraction_object.