python保留两位小数

python保留两位小数

 

python保留两位小数:

复制代码
In [1]: a = 5.026

In [2]: b = 5.000

In [3]: round(a,2)
Out[3]: 5.03

In [4]: round(b,2)
Out[4]: 5.0

In [5]: '%.2f' % a
Out[5]: '5.03'

In [6]: '%.2f' % b
Out[6]: '5.00'

In [7]: float('%.2f' % a)
Out[7]: 5.03

In [8]: float('%.2f' % b)
Out[8]: 5.0

In [9]: from decimal import Decimal

In [10]: Decimal('5.026').quantize(Decimal('0.00'))
Out[10]: Decimal('5.03')

In [11]: Decimal('5.000').quantize(Decimal('0.00'))
Out[11]: Decimal('5.00')
复制代码

这里有三种方法,

round(a,2)
'%.2f' % a
Decimal('5.000').quantize(Decimal('0.00'))

当需要输出的结果要求有两位小数的时候,字符串形式的:'%.2f' % a 方式最好,其次用Decimal。

需要注意的:

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

2. Decimal还可以用来限定数据的总位数。

原文地址:https://www.cnblogs.com/hanbowen/p/10064507.html