在python當中如何保留兩位有效數字?
作者:由 司馬弈 發表于 繪畫時間:2022-09-19
保留兩位小數,並做四捨五入處理
方法一:使用字串格式化
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’]