Simple Introduction
When writing a data platform, it is necessary to make the statistic of passing rate, so it is unavoidable to have decimal condition. At this point, there will be an infinite number of decimals, then how to make a choice?
Actual operation
You can use the decimal module, which is decimal, which provides decimal floating-point arithmetic support.
Common methods
1. Can be passed to a decimal integer or string parameter, but not floating point data, because the floating-point data itself is inaccurate.
2. To convert from floating-point data to decimal type
From decimal Import *
Decimal.from_float (12.222)
# result is decimal (' 12.2219999999999995310417943983338773250579833984375 ')
3. Define the result style by setting a valid number:
From decimal Import *
GetContext (). prec=6
Decimal (1)/decimal (7)
# The result is a decimal (' 0.142857 '), six valid digits
4. Rounding, keeping several decimals
From decimal Import *
Decimal (' 50.5679 '). Quantize (Decimal (' 0.00 '))
# result is decimal (' 50.57 '), result rounding retains two decimal places
5.Decimal result converted to string
From decimal Import *
STR (Decimal (' 3.40 '). Quantize (Decimal (' 0.0 ')))
# result is ' 3.40 ', String type
Effect
Reference:
Decimal module
How Python takes the number of decimal places