Effective Python 读书笔记: 第47条: 在重视精确度的场合,应该使用decimal

# -*- encoding: utf-8 -*-

import decimal

'''
第47条: 在重视精确度的场合,应该使用decimal

关键:
1 python数值
可以表示任意长度的值
round(value, preciseNum):
value: 待处理的值
preciseNum: 保留的小数位个数
最终round结果是向下取整, 3.444取精度保留两位小数的结果是3.44

2 decimal模块
有decimal.Decimal: 提供28个小数位,进行定点计算
用法: decimal.Decimal(numStr),
其中numStr是字符串表示的数字,例如"3.29'
指定精度和舍入方式:
decimal.Decimal.quantize(decimal.Decimal('0.01'), rounding=ROUND_UP)

用法示例:
    rate = decimal.Decimal('1.45')
    time = decimal.Decimal('222')
    result = rate * time / decimal.Decimal('60')
    print result
    # 指定精度和舍入方式
    rounded = result.quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_UP)
    print rounded

3 总结
decimal.Decimal适用于对精度要求很高的场合,或者用户可以自己设定舍入方式的场合


参考:
Effectiv Python 编写高质量Python代码的59个有效方法
'''
def useRound():
    rate = 1.45
    seconds = 3 * 60 + 42
    result = rate * seconds / 60
    print result
    print round(result, 2)


def useDecimal():
    rate = decimal.Decimal('1.45')
    time = decimal.Decimal('222')
    result = rate * time / decimal.Decimal('60')
    print result
    # 指定精度和舍入方式
    rounded = result.quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_UP)
    print rounded


def process():
    useRound()
    useDecimal()


if __name__ == "__main__":
    process() 

猜你喜欢

转载自blog.csdn.net/qingyuanluofeng/article/details/89035739