python中round(四舍五入)的坑

  python中的round函数不能直接拿来四舍五入,一种替代方式是使用Decimal.quantize()函数。

具体内容待补。

>>> round(2.675, 2)
2.67

 可以传递给Decimal整型或者字符串参数,但不能是浮点数据,因为浮点数据本身就不准确

 1 # -*- coding: utf-8 -*-
 2 from decimal import Decimal, ROUND_HALF_UP
 3 
 4 
 5 class NumberUtil(object):
 6     @staticmethod
 7     def _round_by_decimal(number, quantize_exp):
 8         str_num = str(number)
 9         dec_num = Decimal(str_num).quantize(quantize_exp, rounding=ROUND_HALF_UP)
10         return float(dec_num)
11 
12     @staticmethod
13     def round_2_digits_by_decimal(number):
14         return NumberUtil._round_by_decimal(number, Decimal('0.01'))
15 
16     @staticmethod
17     def round_4_digits_by_decimal(number):
18         return NumberUtil._round_by_decimal(number, Decimal('0.0001'))

参考文章:

(1)python中关于round函数的小坑

(2)[python]decimal常用操作和需要注意的地方

原文地址:https://www.cnblogs.com/tlz888/p/10478545.html