python保留两位小数

参考 :

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还可以用来限定数据的总位数。