Related Tags

python
communitycreator

# How to get a fraction from a decimal number in Python

abhilash

### 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 decimal

decimal_value = -5.422

decimal_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 decimal module.
• Line 3: We define a decimal value called decimal_value.
• Line 5: We obtain an instance of the Decimal class called decimal_object for decimal_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.

1. We get a Decimal object for the given decimal value.
2. We use the from_decimal() method to get an instance of the Fractions class.
3. We use the as_integer_ratio() method of the Fractions class to get the numerator and the denominator.

### Code

import fractions, decimal

decimal_value = -5.422

decimal_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 decimal and the fractions module.
• Line 3: We define a decimal value called decimal_value.
• Line 5: We obtain an instance of the Decimal class called decimal_object for the decimal_value.
• Line 7: We create an instance of the Fractions class called fraction_object using the from_decimal method, passing decimal_object as argument.
• Line 9: We get the numerator and the denominator by invoking the as_integer_ratio() on fraction_object.
• Line 11: We print the numerator and denominator.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

abhilash
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time