Python `decimal` Module
This article explains Python's decimal module.
You can learn about the basics of calculations with the decimal module, managing precision, rounding, and more, along with code samples.
YouTube Video
Python decimal Module
Python's decimal module provides fixed-precision decimal arithmetic to avoid errors that occur in floating-point operations. By using this module, more reliable results can be obtained in financial calculations or calculations requiring high accuracy. In situations where errors from the float type are an issue, the decimal module is effective.
Basic Usage of the decimal Module
When using the decimal module, import the Decimal class and handle values as instances of this class. Next, we'll demonstrate the basic usage.
1from decimal import Decimal
2
3# Basic usage example of Decimal
4a = Decimal('0.1')
5b = Decimal('0.2')
6result = a + b
7
8print(f"Result: {result}") # Result: 0.3- This code accurately adds 0.1 and 0.2 using the
Decimalclass. Performing the same calculation with thefloattype results in values with errors, whereasDecimalavoids these errors.
Controlling Precision
The decimal module allows you to easily control the precision (number of decimal places) in calculations. The getcontext() function can be used to retrieve the current context and modify its settings.
1from decimal import Decimal, getcontext
2
3# Set the precision
4getcontext().prec = 4 # Set to 4 decimal places
5
6a = Decimal('1') / Decimal('3')
7print(f"Result with precision 4: {a}") # Result with precision 4: 0.3333- In this example, the precision is set to 4 digits for the calculation of
1 ÷ 3. UsingDecimal, you can set the precision of calculations as needed, allowing you to adjust results accordingly.
Rounding
The decimal module includes several options for specifying rounding methods. The following are examples of using various rounding options such as ROUND_UP and ROUND_DOWN.
1from decimal import Decimal, ROUND_UP, ROUND_DOWN
2
3# Example of rounding a number
4a = Decimal('1.2345')
5
6# Rounding up
7rounded_up = a.quantize(Decimal('0.01'), rounding=ROUND_UP)
8print(f"Rounded Up: {rounded_up}") # Rounded Up: 1.24
9
10# Rounding down
11rounded_down = a.quantize(Decimal('0.01'), rounding=ROUND_DOWN)
12print(f"Rounded Down: {rounded_down}") # Rounded Down: 1.23- Here,
quantize()is used to round up and down numbers to a precision of 2 decimal places. This allows for rounding as well as various other types of rounding methods.
Operational Context and Exceptions
The decimal module can also handle errors and exceptions that occur during operations. Custom handling can be defined for specific errors, such as division by zero or overflow.
1from decimal import Decimal, getcontext, DivisionByZero
2
3# Exception handling
4getcontext().traps[DivisionByZero] = True
5
6try:
7 result = Decimal('1') / Decimal('0')
8except DivisionByZero:
9 print("Division by zero error caught!")- In this example, the
DivisionByZeroexception is caught when a division by zero occurs. In thedecimalmodule, errors can be controlled and customized in this way.
Summary
The decimal module is extremely useful in financial calculations or situations where high precision is required to avoid floating-point errors. It supports a wide range of applications, from basic calculations to precision management, rounding, and exception handling. Review the summarized points below and utilize the decimal module according to your specific needs.
- Accurate decimal arithmetic is possible with the
Decimalclass. - You can freely adjust precision and rounding settings.
- Exceptions such as division by zero can be managed.
This allows you to use the decimal module to minimize errors in situations that require accurate numerical calculations.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.