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'))
參考文章:
(2)[python]decimal常用操作和需要注意的地方