python如何保留指定小数点位数?
发布时间:2026-04-23 15:45:39

Python保留指定小数点位数的方法:
1、使用’%.2f’ %f 方法
f=1.23456
print('%.4f'%f)
print('%.3f'%f)
print('%.2f'%f)结果:
1.2346 1.235 1.23
这种方法将四舍五入
2、format函数
Python2.6 一开始,新增了格式化字符串的函数str.format(),它增强了字符串格式化的功能。
基本语法是通过{}和:取代以前的%。

print(format(1.23456,'.2f')) print(format(1.23456,'.3f')) print(format(1.23456,'.4f'))
输出结果:
1.23 1.235 1.2346
3、round()函数
round()方法返回浮点x的四舍五入值。
以下是 round() 语法方法:语法方法:
round(x[,n])
参数:
x -- 数值表达式。
n -- 数值表达式。
a=1.23456 b=2.355 c=3.5 d=2.5 print(round(a,3)) print(round(b,2)) print(round(c)) print(round(d))
输出结果:
1.235#1.23456终于向前移动 2.35#2.355 4#最后3.5变成了4。 2#最终2.5值变为2.5值
请关注Python视频教程栏目,了解更多Python知识。
下一篇 python如何查找在线帮助?
