Detailed explanation of the usage of Python decimal module

Decimal module: decimal means decimal, this module provides decimal floating point arithmetic support

  1. It can be passed to Decimal integer or string parameters, but it cannot be floating-point data, because floating-point data itself is not accurate.

  2. To convert from floating point data to Decimal type

from decimal import *
Decimal.from_float(12.222)

The result is Decimal('12.2219999999999995310417943983338773250579833984375')

  1. Limit the result style by setting significant figures

from decimal import *
getcontext().prec = 6
Decimal(1)/Decimal(7)

The result is Decimal('0.142857'), six significant digits

  1. Round to the nearest whole number, keep a few decimal places

from decimal import *
Decimal(‘50.5679’).quantize(Decimal(‘0.00’))

The result is Decimal('50.57'), and the result is rounded to two decimal places

  1. Decimal result is converted to string

from decimal import *
str(Decimal(‘3.40’).quantize(Decimal(‘0.0’)))

The result is '3.4', string type

Example of decimal processing calculation accuracy problem in Python3

#! /usr/bin/python3
# coding:utf-8import decimal
from decimal import Decimal, getcontext

def demo():"""
 Rounding problem:
 ROUND_CEILING always goes to infinity and rounds up
  ROUND_DOWN always rounds towards 0
  ROUND_FLOOR always tends to negative infinity and rounds down
  ROUND_HALF_DOWN If the last valid digit is greater than or equal to 5, round towards 0; otherwise, round towards 0
  ROUND_HALF_EVEN is similar to ROUND_HALF_DOWN, however, if the last valid digit value is 5, the previous digit will be checked.
   Even values will cause the result to be rounded down, and odd values will cause the result to be rounded up
  ROUND_HALF_UP is similar to ROUND_HALF_DOWN, but if the last valid digit is 5, the value will be rounded to the opposite direction of 0
  ROUND_UP rounded to the opposite direction of 0
  ROUND_05UP If the last digit is 0 or 5, round to the opposite direction of 0; otherwise round to 0
  """

 # 1. Routine calculation
 getcontext().prec =9
 r1 =Decimal(1)/Decimal(3)print("r1 ", r1) # r1 0.333333333

 # 2. But getcontext().prec will contain all the lengths before the decimal point, and the number of digits after the decimal point cannot be fixed when the front length changes
 r2 =Decimal(10)/Decimal(3)print("r2 ", r2) # r2 3.33333333

 # 3. If you want to control the number of digits after the decimal point, you need to use decimal.quantize(Decimal('0.00000000')), Note that it cannot exceed getcontext().number of prec
 r3 =Decimal(1)/Decimal(3)print("r3 ", r3.quantize(Decimal('0.00000000'))) # r3 0.33333333
 r4 =Decimal(10)/Decimal(3)print("r4 ", r4.quantize(Decimal('0.00000000'))) # r4 3.33333333
 r5 =Decimal(10)/Decimal(str(1.5))print("r5 ", r5.quantize(Decimal('0.00000000'))) # r5 6.66666667

 # 4. Rounded up
 getcontext().rounding =getattr(decimal,'ROUND_CEILING') #Always round up towards infinity
 r6 =Decimal(10)/Decimal(str(1.5)) # r6 6.66666667print("r6 ", r6.quantize(Decimal('0.00000000')))
 r7 =Decimal(10)/Decimal(3) # r7 3.33333334print("r7 ", r7.quantize(Decimal('0.00000000')))

 # 5. Round down
 getcontext().rounding =getattr(decimal,'ROUND_FLOOR') #Always round down towards infinity
 r8 =Decimal(10)/Decimal(str(1.5)) # r8 6.66666666print("r8 ", r8.quantize(Decimal('0.00000000')))
 r9 =Decimal(10)/Decimal(3) # r9 3.33333333print("r9 ", r9.quantize(Decimal('0.00000000')))if __name__ =='__main__':demo()

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Detailed explanation of the usage of Python decimal module
Detailed explanation of the principle of Python super() method
Detailed explanation of python standard library OS module
Detailed explanation of the principle of Python function parameter classification
Detailed explanation of the principle of Python timer thread pool
Detailed explanation of the implementation steps of Python interface development
Detailed explanation of Python web page parser usage examples
Detailed explanation of the attribute access process of Python objects
Detailed explanation of the remaining problem based on python (%)
The usage of wheel in python
Detailed explanation of python sequence types
Detailed usage of dictionary in Python
The usage of tuples in python
The usage of Ajax in Python3 crawler
Detailed explanation of Python IO port multiplexing
Detailed usage of Python virtual environment venv
Detailed explanation of -u parameter of python command
Detailed explanation of Python guessing algorithm problems
Python3 built-in module usage
Detailed explanation of the use of pip in Python | summary of third-party library installation
The meaning and usage of lists in python
Detailed explanation of how python supports concurrent methods
Python—requests module detailed explanation
Detailed explanation of data types based on Python
Prettytable module of python
Detailed explanation of common tools for Python process control
Consolidate the foundation of Python (4)
Consolidate the foundation of Python(7)
Consolidate the foundation of Python(6)
Consolidate the foundation of Python(5)
matplotlib of python drawing module
Consolidate the foundation of Python (3)
Detailed implementation of Python plug-in mechanism
Detailed explanation of ubuntu using gpg2
Python handles the 4 wheels of Chinese
Python error handling assert detailed explanation
Python simulation of the landlord deal
What is the use of Python
Usage of os package in python
Simple usage of python definition class
​Full analysis of Python module knowledge
The premise of Python string pooling
Secrets of the new features of Python 3.8
How to view the python module
The father of Python joins Microsoft
The operation of python access hdfs
End the method of running python
Python learning os module and usage
Detailed explanation of the installation and use of SSH in the Ubuntu environment
Understanding the meaning of rb in python
Can Python implement the structure of the stack?
Learn the basics of python interactive mode
What are the required parameters of python
Python3 module
Logistic regression at the bottom of python
Python solves the Tower of Hanoi game
Solve the conflict of multiple versions of python
What is the scope of python variables
Python implements the sum of fractional sequences
Detailed analysis of Python garbage collection mechanism
Two days of learning the basics of Python