參考 :
https://www.cnblogs.com/Raymon-Geng/p/5784290.html
使用python內置的round函數
1 In [1]: a = 5.026 2 3 In [2]: b = 5.000 4 5 In [3]: round(a,2) 6 Out[3]: 5.03 7 8 In [4]: round(b,2) 9 Out[4]: 5.0 10 11 In [5]: '%.2f' % a 12 Out[5]: '5.03' 13 14 In [6]: '%.2f' % b 15 Out[6]: '5.00' 16 17 In [7]: float('%.2f' % a) 18 Out[7]: 5.03 19 20 In [8]: float('%.2f' % b) 21 Out[8]: 5.0 22 23 In [9]: from decimal import Decimal 24 25 In [10]: Decimal('5.026').quantize(Decimal('0.00')) 26 Out[10]: Decimal('5.03') 27 28 In [11]: Decimal('5.000').quantize(Decimal('0.00')) 29 Out[11]: Decimal('5.00')
這里有三種方法,
round(a,2)
'%.2f' % a
Decimal('5.000').quantize(Decimal('0.00'))
當需要輸出的結果要求有兩位小數的時候,字符串形式的:'%.2f' % a 方式最好,其次用Decimal。
需要注意的:
1. 可以傳遞給Decimal整型或者字符串參數,但不能是浮點數據,因為浮點數據本身就不准確。
2. Decimal還可以用來限定數據的總位數。
