python 保留两位小数的方法

使用 round() 函数

x = 3.14159265
print(round(x, 2))  # 输出3.14

使用 format() 函数

x = 3.14159265
# f 代表浮点数
print("{:.2f}".format(x))  # 输出3.14

使用 % 格式化字符串

x = 3.14159265
print("%.2f" % x)  # 输出3.14

使用 decimal 模块的 Decimal 类

不推荐使用

from decimal import Decimal

x = 3.14159265
print(Decimal(x).quantize(Decimal('0.00')))

你可能感兴趣的:(python)