# coding=utf-8
from decimal import Decimal, getcontext
# 1.可以传递给Decimal整型或者字符串参数,但不能是浮点数据,因为浮点数据本身就不准确。
# 传入浮点数 5.55
a = Decimal(5.55)
print('a = ', a)
a = a * 100
print('a = ', a)
# 传入字符串 ‘5.55’
b = Decimal('5.55')*100
print('b = ', b)
>>> a = 5.54999999999999982236431605997495353221893310546875
>>> a = 554.9999999999999822364316060
>>> b = 555.00
# 2.要从浮点数据转换为Decimal类型
c = Decimal.from_float(22.222)
print('c = ', c)
>>> c = 22.22200000000000130739863379858434200286865234375
# 3.getcontext().prec设置有效数字的个数。
# 通过设定有效数字,限定结果样式
getcontext().prec = 4
x1 = Decimal(1) / Decimal(3) # 结果为Decimal('0.3333'),四个有效数字
print('x1 = ', x1)
x2 = Decimal(100) / Decimal(3)
print('x2 = ', x2)
x3 = Decimal(700000)/Decimal(9)
print('x3 = ', x3)
>>> x1 = 0.3333
>>> x2 = 33.33
>>> x3 = 7.778E+4
# 注意:
# 如果prec的长度比数字的长度小的时候,*100得出的数就不对了
num = '88.8888'
f = Decimal(num)
print('f = ', f)
g = f * 100
print('g = ', g)
h = Decimal('999.999')
print('h = ', h)
>>> f = 88.8888
>>> g = 8889
>>> h = 999.999
# 4.四舍五入,保留几位小数
d = Decimal('50.5679').quantize(Decimal('0.00'))
print('d = ', d) # 结果为Decimal('50.57'),结果四舍五入保留了两位小数
>>> d = 50.57
# 5.Decimal 结果转化为string
e = str(Decimal('3.40').quantize(Decimal('0.0')))
print('e = ', e)
>>> e = 3.4
# 6.decimal模块进行十进制数学计算
i = Decimal('4.20') + Decimal('2.10') + Decimal('6.30')
print('i = ', i)
>>> i = 12.60
# 当然精度提升的同时,肯定带来的是性能的损失。在对数据要求特别精确的场合(例如财务结算),这些性能的损失是值得的。
# 但是如果是大规模的科学计算,就需要考虑运行效率了。毕竟原生的float比Decimal对象肯定是要快很多的。
x = Decimal('-3.1415926535') + Decimal('-2.7182818285')
print x
print x.quantize(Decimal('1.0000'), ROUND_HALF_EVEN)
print x.quantize(Decimal('1.0000'), ROUND_HALF_DOWN)
print x.quantize(Decimal('1.0000'), ROUND_CEILING)
print x.quantize(Decimal('1.0000'), ROUND_FLOOR)
print x.quantize(Decimal('1.0000'), ROUND_UP)
print x.quantize(Decimal('1.0000'), ROUND_DOWN)
output:
-5.8598744820
-5.8599
-5.8599
-5.8598
-5.8599
-5.8599
-5.8598
https://www.cnblogs.com/piperck/p/5843253.html
https://blog.csdn.net/weixin_37989267/article/details/79473706
总结: