python中四舍五入精度问题

python存float的时候如财务数据等需要四舍五入两位数,但是python自带的四舍五入方法偶尔会存在“五舍六入”,提供两种处理函数

from decimal import Decimal, ROUND_HALF_UP
def round_dec(n, d=2):
s = '0.' + '0' * d
return Decimal(str(n)).quantize(Decimal(s), rounding=ROUND_HALF_UP)
print(round_dec(3.545,2))

# 保留两位小数
def myRound(res):
if res=="" or res==0:
returnData=0.00
else:
if isinstance(res,float):
new_res=res*100
returnData=round(new_res)/100
elif isinstance(res,str):
new_res=float(res.replace(',',''))*100
returnData = round(new_res) / 100
else:
new_res=res*100
returnData = round(new_res) / 100
return str(returnData)
原文地址:https://www.cnblogs.com/alecc1124/p/13345642.html