Set the max digit of Decimal objects in Python (getcontext().prec)

You can divide a Decimal object by a Decimal object. The result is also a Decimal object.

from decimal import Decimal

a = Decimal(1) / Decimal(13)

print(type(a))  # <class 'decimal.Decimal'>
print(a)  # 0.07692307692307692307692307692

If you want to show it with only 3 digits, use the getcontext() in the decimal module.

from decimal import Decimal, getcontext

getcontext().prec = 3
a = Decimal(1) / Decimal(13)

print(a)  # 0.0769

The getcontext() returns the current context and you can set its properties. prec is a property setting the max digit of Decimal objects.

from decimal import Decimal, getcontext

getcontext().prec = 3

a1 = Decimal(5) / Decimal(7)
a2 = Decimal(9) / Decimal(7)
a3 = Decimal(100) / Decimal(7)
a4 = Decimal(10) / Decimal(5)

print(a1)  # 0.714
print(a2)  # 1.29
print(a3)  # 14.3
print(a4)  # 2

Comments

Powered by Markdown