Decimal module: Processing of decimal
There is a large error in the float type with the decimal number in Python, which requires a decimal module to handle it.
definition of decimal:
>>> fromdecimalimport*
>>>x=decimal (' 0.70 ') *decimal (' 1.05 ')
>>> x
Decimal (' 0.7350 ')
Note: The str type is generally converted to the decimal type instead of float directly.
Rounding methods for decimal:
#quantize: Round method in the decimal module
>>> x.quantize (Decimal (' 0.01 ')) #round to nearest cent
Decimal (' 0.74 ')
>>>decimal (' 7.325 '). Quantize (Decimal (' 1. '), rounding=round_up)
Decimal (' 8 ')
Rounding mode: round_ceiling, Round_down, Round_floor, Round_half_down,round_half_even, Round_half_up, ROUND_UP, and ROUND_05UP .
Configuration changes:
# GetContext Method: View and set basic parameters. For example, set the exact digits of the desired decimal number.
>>> GetContext (). prec=36 >>> Decimal (1)/decimal (7) Decimal (' 0.142857142857142857142857142857142857 ') GetContext (). Rounding = Round_up |
The transformation of the whole:
My_context=context (Prec=60,rounding=round_half_down) SetContext (My_context) #转换为my_context #模块自定义了常量BasicContext, Extendedcontext,defaultcontext. #本质: Extendedcontext =getcontext (Basiccontext). Clear_flags () SetContext (Extendedcontext) #转换为ExtendedContext |
other-string forwards for decimal:
data = Map (Decimal, ' 1.34 1.87 3.45 2.351.00 0.03 9.25 '. Split ())