Python取整及四舍五入

  • 向上取整:math.ceil()
import math
 
math.ceil(-0.9)
>>> 0
 
math.ceil(0.3)
>>> 1
  • 向下取整:math.floor()、int()、//(整除)
math.floor(-0.3)
>>> -1

int(0.9)
>>> 0

3 // 2  # 1.5
>>> 1
  • 虚假的四舍五入:round()
"""
对小数末尾为5的处理方法:
当末尾的5的前一位为奇数:向绝对值更大的方向取整(比如-1.5、1.5处理结果);当末尾的5的前一位为偶数:去尾取整(比如-2.5和2.5的处理结果)。
"""
round(-2.5) >>> -2 round(-1.5) >>> -2 round(1.5) >>> 2 round(2.5) >>> 2
  • 真正的四舍五入:int(n+0.5)
    
    

 

posted on 2023-06-08 22:01  shui00cc  阅读(421)  评论(1编辑  收藏  举报