python中四捨五入精度問題

2022-07-02 08:33:10 字數 737 閱讀 2123

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)

python關於四捨五入的精度問題

print round 1.5 round 2.5 round 3.5 輸出為 2,2,4from decimal import decimal,round half up defround dec n,d 2 s 0.0 d return decimal str n quantize decima...

qt的四捨五入 Qt(C )四捨五入

qt現在是四捨六入五成雙,要想四捨五入得自己想辦法,實現如下 include include double c1 3.435 double c2 3.445 double c3 3.4351 double c4 3.4451 double c5 3.445 qdebug qdebug qdebug ...

mysql 金額 四捨五入 mysql四捨五入

雲資料庫 mysql 雲資料庫 rds for mysql 是穩定可靠 可彈性伸縮的雲資料庫服務。通過雲資料庫能夠讓您幾分鐘內完成資料庫部署。雲端完全託管,讓您專注於應用程式開發,無需為資料庫運維煩惱 低至 0.24 小時起,買1年83折 雲資料庫mysql 雲資料庫 rds for mysql 是...