python怎么设置小数点后保留两位小数点
发布时间:2026-04-08 15:33:31

在python中设置保留两位小数点的方法:
1、使用字符串格式化
a=12.345
print("%.2f"%a)
#12.352、使用round内置函数
a=12.345 a1=round(a,2) print(a1) #12.35
3、使用decimal模块
fromdecimalimportDecimal
a=12.345
Decimal(a).quantize(Decimal("0.00"))
Decimal('12.35')4、在序列中使用切片
a=12.345
str(a).split('.')[0]+'.'+str(a).split('.')[1][:2]
'12.34'5、使用re模块
importre
a=12.345
re.findall(r"\d{1,}?\.\d{2}",str(a))
['12.34']请关注Python视频教程栏目,了解更多Python知识。
下一篇 python怎么让代码无效
