
python中设置保留两位小数点的方法:
1、使用字符串格式化
a = 12.345
print("%.2f" % a)
# 12.35
2、使用round内置函数
a = 12.345 a1 = round(a, 2) print(a1) # 12.35
3、使用decimal模块
from decimal import Decimal
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模块
import re
a = 12.345
re.findall(r"\d{1,}?\.\d{2}", str(a))
['12.34']
更多Python知识请关注Python视频教程栏目。
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试



