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常用操作和需要注意的地方

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM