問題描述:
round(float [,n])函數(shù)用于返回浮點數(shù)四舍五入后的值演怎,小數(shù)點后保留n位(默認(rèn)為0)
例如:
round(3.5248,2) > 3.52
但是當(dāng)保留 n 位時,第 n+1 位為數(shù)字 5逻炊,此時它并不會進(jìn)一位丝蹭,而是舍棄掉慢宗。
例如:
round(3.585,2) > 3.58
假如 第 n+1 位的數(shù)字 > 5,又能正常顯示:
round(3.586,2) >3.59
原因解釋:
這并不是BUG,在 Python 手冊中這樣說到:
The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
簡單來說奔穿,有些浮點數(shù)在計算機中并不能像整數(shù)那樣被準(zhǔn)確表達(dá)镜沽,它可能是近似值。
解決辦法:
使用 decimal 模塊