Decimal Type

The decimal object was introduced in Python 2.4. Decimals function are like floating-point numbers, but they have a fixed number of decimal points. Decimals are fixed-precision floating-point values. The decimal type is well suited to representing fixed-precision quantities like sums of money and can help you achieve better numeric accuracy.

Decimal basics

Floating-point math is less than exact because of the limited space used to store values. The following should be zero, but it it not:

``````>>> 0.3 + 0.3 + 0.3 - 0.9
-1.1102230246251565e-16
# Python 3.5.2``````

With decimals, the result is different:

``````# Making decimal objects
>>> from decimal import Decimal
>>> Decimal('0.3') + Decimal('0.3') + Decimal('0.3') - Decimal('0.9')
Decimal('0.0')``````

Setting decimal precision globally

A context object in the `decimal` module allows for specifying precision (number of decimal digits) :

``````>>> import decimal
>>> decimal.Decimal(3) / decimal.Decimal(7)
Decimal('0.4285714285714285714285714286')
>>> decimal.getcontext().prec = 4
>>> decimal.Decimal(3) / decimal.Decimal(7)
Decimal('0.4286')
>>> decimal.getcontext().prec = 2
>>> decimal.Decimal(3) / decimal.Decimal(7)
Decimal('0.43')``````

Decimal context manager

It is possible to reset precision temporarily by using the `with` context manager statement.

``````>>> import decimal
>>> decimal.Decimal('1.00') / decimal.Decimal('3.00')
Decimal('0.3333333333333333333333333333')
>>> with decimal.localcontext() as ctx:
...     ctx.prec = 2
...     decimal.Decimal('1.00') / decimal.Decimal('3.00')
...
Decimal('0.33')
>>>
>>> decimal.Decimal('1.00') / decimal.Decimal('3.00')
Decimal('0.3333333333333333333333333333')``````