decimal | Python Standard Library – Real Python

The Python decimal module provides support for correctly rounded decimal floating-point arithmetic. It offers several advantages over the built-in floating-point type, including preserving significant digits.

This module allows you to make precise calculations in finance and other fields that require accurate decimal representation.

Here’s a quick example:

Key Features

  • Provides a Decimal data type for decimal floating-point arithmetic
  • Supports arbitrary precision arithmetic
  • Offers configurable rounding modes
  • Supports exact decimal representation of numbers
  • Provides context objects for controlling precision and rounding

Frequently Used Classes and Functions

Rounding modes:

Mode Rounds
decimal.ROUND_CEILING Towards postive infinity
decimal.ROUND_DOWN Towards zero
decimal.ROUND_FLOOR Towards negative infinity
decimal.ROUND_HALF_DOWN To nearest, with ties rounding toward zero
decimal.ROUND_HALF_EVEN To nearest, with ties going to nearest even integer
decimal.ROUND_HALF_UP To nearest, with ties rounding away from zero
decimal.ROUND_UP Away from zero
decimal.ROUND_05UP Away from zero if the digit dropped is 0 or 5. Otherwise, rounds towards zero

Examples

Creating a Decimal object for precise arithmetic:

Setting precision for calculations:

Common Use Cases

  • Performing precise financial calculations
  • Handling user input that requires exact decimal representation
  • Avoiding rounding errors in scientific computations
  • Implementing configurable rounding strategies

Real-World Example

Suppose you need to calculate the total cost of items in a shopping cart with precise financial calculations:

This example demonstrates how the decimal module can be used to sum up monetary values accurately, avoiding the pitfalls of binary floating-point representation.

Tutorial

Numbers in Python

In this tutorial, you'll learn about numbers and basic math in Python. You'll explore integer, floating-point numbers, and complex numbers and see how perform calculations using Python's arithmetic operators, math functions, and number methods.

basics python

For additional information on related topics, take a look at the following resources: