python模块: decimal

1. decimal

from decimal import Decimal

# 设置小数位数
m = Decimal('0.000')
print(m, type(m))
# 0.000 <class 'decimal.Decimal'>

# 将浮点数转换为decimal类型
x = Decimal.from_float(float(20.45) * 1.50)
print(x, type(x))
# 30.6749999999999971578290569595992565155029296875 <class 'decimal.Decimal'>

y = x.quantize(Decimal('0.000'))  # quantize量化的意思
print(y, type(y))
# 30.675 <class 'decimal.Decimal'>

zt = float(Decimal.from_float(float(20.45) * 1.50).quantize(Decimal('0.00')))
print(zt, type(zt))
# 30.67 <class 'float'>

  

 

posted @ 2020-10-10 11:21  Adamanter  阅读(252)  评论(0)    收藏  举报