天天看點

python保留兩位小數_python保留兩位小數

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')

python保留兩位小數_python保留兩位小數

這裡有三種方法,

round(a,2)

'%.2f' % a

Decimal('5.000').quantize(Decimal('0.00'))

當需要輸出的結果要求有兩位小數的時候,字元串形式的:'%.2f' % a 方式最好,其次用Decimal。

需要注意的:

1. 可以傳遞給Decimal整型或者字元串參數,但不能是浮點資料,因為浮點資料本身就不準确。

2. Decimal還可以用來限定資料的總位數。