今天做了一個題要求四舍五入,然后找了一個方法:round()可以四舍五入,
試了試1.5---》2
試了試0.5---》0 !!!!
找了幾個方法說可以的:
# 方法一: from _pydecimal import Decimal, Context, ROUND_HALF_UP print(Context(prec=3, rounding=ROUND_HALF_UP).create_decimal('1.32545454544')) # 方法二: print(round(1.32545454544* 100) / 100.0) 輸出: 1.33
但是!!但是!!但是!!
輸入0.5結果是0.5 ( 這個可以通過設置格式得到,原來不知道)
沒辦法,對於有些可以,有些不可以,主要是存儲十進制的時候二進制有偏差,怎么辦!?
這里我自己鼓搗出一個方法(在數后面加一個很小的數,不影響計算的那種如:0.000000000001)
print(round(0.5+0.00000000000001)) 結果 1
另外可以用下面方法:
========================================================最新更新=====================================================================
decimal函數使用:
decimal()函數是用於十進制精確計算的,為的是防止浮點數后面位數不准確導致計算結果出現偏差
prec : 設置精度(有效數字位數)
rounding : 設置舍入舍出方式
有多種方法

ROUND_CEILING (towards Infinity), ROUND_DOWN (towards zero), ROUND_FLOOR (towards -Infinity), ROUND_HALF_DOWN (to nearest with ties going towards zero), ROUND_HALF_EVEN (to nearest with ties going to nearest even integer), ROUND_HALF_UP (to nearest with ties going away from zero), or ROUND_UP (away from zero). ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)
設定小數位數
Decimal('1.2346568355').quantize(Decimal('0.00'))
設定有效數字
getcontext().prec = 4
參考:
https://blog.csdn.net/qq_34979346/article/details/83827044
https://www.cnblogs.com/piperck/p/5843253.html
https://finthon.com/python-decimal/