問題:
python正常的除法運算:
3/2=1.5
python的取整運算:捨棄小數點,取整數部分。
3//2=1
4//3=1
上述方法無法解決四捨五入的整數問題。
常用的解決方法:
- round(number, ndigits=None)
- The return value is an integer if ndigits is omitted(省略) or None.
- 否則,就保留指定小數位。
一般情況下,能夠解決大多數問題;但是,round對於0.5這個精度處理的方式有些特殊:
round(3.5)=4
round(4.5)=4
round(4.55,1)=4.5
round(4.45,1)=4.5
round(3.45,1)=3.5
round(3.55,1)=3.5
在python中,四捨五入有幾種模式:一般採用的是decimal.ROUND_HALF_EVEN;(
向“最接近的”數字舍入,如果與兩個相鄰數字的距離相等,則向相鄰的偶數舍入。此舍入模式也稱爲“銀行家舍入法”,主要在美國使用。四捨六入,五分兩種情況。)
Rounding modes
decimal.
ROUND_CEILING
Round towards
Infinity
.
decimal.
ROUND_DOWN
Round towards zero.
decimal.
ROUND_FLOOR
Round towards
-Infinity
.
decimal.
ROUND_HALF_DOWN
Round to nearest with ties going towards zero.
decimal.
ROUND_HALF_EVEN
Round to nearest with ties going to nearest even integer.
decimal.
ROUND_HALF_UP
Round to nearest with ties going away from zero.
decimal.
ROUND_UP
Round away from zero.
decimal.
ROUND_05UP
¶Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero.
想要通過round來進行極其精確的處理,貌似不太可能,不過對於大多數的情況已經足以應對。