📜  python 格式只有 1 个小数位 - Python (1)

📅  最后修改于: 2023-12-03 15:04:17.520000             🧑  作者: Mango

Python 格式只有 1 个小数位

在 Python 中,可以使用 round() 函数将一个浮点数四舍五入为指定小数位数,这时候如果希望保留一位小数,可以将参数 ndigits 设置为 1

x = 3.1415926
rounded_x = round(x, 1)  # 保留 1 位小数
print(rounded_x)  # 3.1

需要注意的是,round() 的默认行为是保留到最近的偶数,这个特性有时候需要我们特别留意。

a = 2.25
b = 3.25
print(round(a))  # 2
print(round(b))  # 3

同时,如果需要在文本中显示浮点数,可以使用 .format() 方法,以及格式字符串里的格式化参数 :.1f

x = 3.1415926
print("保留一位小数:{:.1f}".format(x))  # 保留一位小数:3.1

总之,在 Python 中,对于需要限制浮点数小数位数的场景,round().format() 是两个非常重要的工具。