情况一:保留两位小数,并做四舍五入处理
1、使用字符串格式化
>>> a=12.345
>>> print("%.2f" %a)
12.35
2、使用round内置函数
>>> a=12.345
>>> round(a,2)
12.35
情况二:保留两位小数,无需四舍五入处理
1、使用序列中切片
>>> a=12.345
>>> str(a).split('.')[0]+'.'+str(a).split('.')[1][0:2]
'12.34'
2、使用re模块
>>> a=12.345
>>> re.match(r'\d+.\d{2}',str(a))
<re.Match object; span=(0, 5), match='12.34'>
网友评论