The decimal module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the float datatype:

  • Decimal is based on a floating-point model but also provide an arithmetic that works in the same way as the arithmetic that people learn at school.
  • Decimal numbers can be represented exactly. In contrast float number not have exact representations. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point. In decimal floating point, 0.1 + 0.1 + 0.1 – 0.3 is exactly equal to zero. In binary floating point, the result is 5.5511151231257827e-017.

A decimal number is immutable. It has a sign, coefficient digits, and an exponent. Precision of the answer also can be adjusted.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import decimal
# Setting the precision Globally
decimal.getcontext().prec = 3
division = decimal.Decimal(72) / decimal.Decimal(7)
print(division)
with decimal.localcontext() as ctx:
# Setting precision in locally
ctx.prec = 3
division = decimal.Decimal(72)
print(division)
import decimal # Setting the precision Globally decimal.getcontext().prec = 3 division = decimal.Decimal(72) / decimal.Decimal(7) print(division) with decimal.localcontext() as ctx: # Setting precision in locally ctx.prec = 3 division = decimal.Decimal(72) print(division)
import decimal

# Setting the precision Globally
decimal.getcontext().prec = 3

division = decimal.Decimal(72) / decimal.Decimal(7)
print(division)

with decimal.localcontext() as ctx:
  # Setting precision in locally 
  ctx.prec = 3
  division = decimal.Decimal(72)
  print(division)