https://blog.csdn.net/Jerry_1126/article/details/85009810
保留兩位小數,並做四舍五入處理
方法一: 使用字符串格式化
>>> a = 12.345
>>> print("%.2f" % a)
12.35
>>>
方法二: 使用round內置函數
>>> a = 12.345
>>> round(a, 2)
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']
————————————————
版權聲明:本文為CSDN博主「傑瑞26」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/Jerry_1126/article/details/85009810