python 保留两位小数方法

原博客连接:https://blog.csdn.net/Jerry_1126/article/details/85009810

保留两位小数,并做四舍五入处理

方法一:使用字符串格式化

a = 12.345
print("%.2f" % a)

# 12.35

方法二: 使用round内置函数

a = 12.345
a1 = round(a, 2)
print(a1)

# 12.35

方法三: 使用decimal模块

from decimal import Decimal
a = 12.345
Decimal(a).quantize(Decimal("0.00"))
Decimal('12.35')

仅保留两位小数,无需四舍五入

方法一: 使用序列中切片

a = 12.345
str(a).split('.')[0] + '.' + str(a).split('.')[1][:2]
'12.34'

方法二: 使用re模块

import re
a = 12.345
re.findall(r"\d{1,}?\.\d{2}", str(a))
['12.34']

猜你喜欢

转载自www.cnblogs.com/zhzhlong/p/10732218.html
今日推荐