Python 中的round函數


在python2.7的doc中,round()的最后寫着,

"Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0." 

保留值將保留到離上一位更近的一端(四舍六入),如果距離兩端一樣遠,則保留到離0遠的一邊。所以round(0.5)會近似到1,而round(-0.5)會近似到-1。



但是到了python3.5的doc中,文檔變成了

"values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice." 

如果距離兩邊一樣遠,會保留到偶數的一邊。比如round(0.5)和round(-0.5)都會保留到0,而round(1.5)會保留到2。

 

Python 2.7 中的結果如下:

>>> round(-0.5)
-1.0
>>> round(0.5)
1.0
>>> round(1.5)
2.0
>>> round(2.5)
3.0
>>> round(3.5)
4.0
>>> round(4.5)
5.0
>>> round(6.5)
7.0

 

Python 3.8 中的結果如下:

round(-0.5)
0
round(0.5)
0
round(1.5)
2
round(2.5)
2
round(3.5)
4
round(4.5)
4
round(5.5)
6
round(6.5)
6


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM