> 文章列表 > python限定位数的小数输出:round,%.2f , decimal

python限定位数的小数输出:round,%.2f , decimal

python限定位数的小数输出:round,%.2f , decimal

四舍五入时

round在位数不足时不会补0,%.2f会补0,decimal会去除多余的0

n =  13.0
nn = 13.23456
print(round(n, 2), round(nn, 2))
print('%.2f'%n, '%.2f'%nn)
import decimal
print(decimal.Decimal(n),decimal.Decimal(nn))
print(decimal.Decimal(nn).quantize(decimal.Decimal('0.00'))) #使用 quantize() 方法将其保留两位小数 #decimal.Decimal 创建了一个 Decimal 类型的数, 小数位数为2位

输出是

13.0 13.23
13.00 13.23
13 13.2345600000000001017497197608463466167449951171875
13.23

数字计算时

float和decimal的区别:

在数字计算中,float 类型是一种二进制浮点数,具有一定的精度误差,而 decimal.Decimal 类型则是一种十进制浮点数,可以精确表示小数点后的位数。

使用float:

a = 1 / 3
print(a) # 输出 0.3333333333333333

使用decimal:

import decimal
a = decimal.Decimal(1) / decimal.Decimal(3)
print(a) # 输出 0.3333333333333333333333333333