Trusted answers to developer questions

abhilash

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 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))

- 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.

`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.- We get a
`Decimal`

object for the given decimal value. - We use the
`from_decimal()`

method to get an instance of the`Fractions`

class. - We use the as_integer_ratio() method of the
`Fractions`

class to get the numerator and the denominator.

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))

- 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

Related Courses