Get the numerator and denominator representing the decimal in Python

The as_integer_ratio() in Decimal methods returns the integer pair representing the value.

from decimal import Decimal

d1 = Decimal('7.5')
d2 = Decimal('0.6')

print(d1.as_integer_ratio())  # (15, 2)
print(d2.as_integer_ratio())  # (3, 5)

The first value devided by the second value is equal to the decimal value.

Using Fraction

from decimal import Decimal
from fractions import Fraction

d = Decimal('2.5')
f = Fraction(d)

print(f)  # 5/2
print(f.numerator)  # 5
print(f.denominator)  # 2

A Fraction object can take the decimal argument. It has numerator and denominator properties.


Powered by Markdown