1. 程式人生 > >【Python】decimal模組

【Python】decimal模組

1.可以傳遞給Decimal整型或者字串引數,但不能是浮點資料,因為浮點資料本身就不準確。

2.要從浮點資料轉換為Decimal型別

3.通過設定有效數字,限定結果樣式:

4.四捨五入,保留幾位小數

from decimal import *

Decimal.from_float(12.222)
Out[279]: Decimal('12.2219999999999995310417943983338773250579833984375')

getcontext().prec = 6

Decimal.from_float(12.222)
Out[281]: Decimal('12.2219999999999995310417943983338773250579833984375')

Decimal.from_float(12.222).quantize(Decimal('0.00'))
Out[282]: Decimal('12.22')
5. 計算Decimal和float相加
a=Decimal(12.323)
a
Out[284]: Decimal('12.32300000000000039790393202565610408782958984375')

b=1.232
a+b
Traceback (most recent call last):
  File "<ipython-input-286-f1d53b280433>", line 1, in <module>
    a+b
TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'

a+Decimal(b)
Out[287]: Decimal('13.5550')