python的取整函数:向上取整,向下取整,四舍五入,分开取整

python中取整数的四种方法
更新于: 2022-04-27 23:08:53

知识点

  • math.ceil: 向上取整
  • math.floor: 向下取整
  • math.round:  四舍五入
  • math.modf: 分开取
  • python采用 IEEE 754 规范来存储浮点数(所以也有小数不精确问题)

代码如下

#encoding:utf-8
import math

#向上取整
print "math.ceil---"
print "math.ceil(2.3) => ", math.ceil(2.3)
print "math.ceil(2.6) => ", math.ceil(2.6)

#向下取整
print "\nmath.floor---"
print "math.floor(2.3) => ", math.floor(2.3)
print "math.floor(2.6) => ", math.floor(2.6)

#四舍五入
print "\nround---"
print "round(2.3) => ", round(2.3)
print "round(2.6) => ", round(2.6)

#这三个的返回结果都是浮点型
print "\n\nNOTE:every result is type of float"
print "math.ceil(2) => ", math.ceil(2)
print "math.floor(2) => ", math.floor(2)
print "round(2) => ", round(2)

取小数,整数分开

import math
math.modf(4.25)
# (0.25, 4)

参考