python小数取整方法总结

1.向下取整,用int()

print(int(-2.33))
print(int(2.22))

"""
-2
2
"""

2.向上取整,用math模块的ceil()

print(math.ceil(-2.77))
print(math.ceil(2.22))
print(math.ceil(3.75))

"""
-2
3
4
"""

3.四舍五入,用round()

print(round(2.44))
print(round(3.66))
print(round(3.66, 1))
print(round(3.663, 2))

"""
2
4
3.7
3.66
"""

4.分别取整数部分和小数部分,用math模块的modf()

print(math.modf(4.25))
print(math.modf(-8.45))

"""
(0.25, 4.0)
(-0.4499999999999993, -8.0)
"""

补充:
计算机中是无法精确的表示浮点数,至少目前的计算机做不到这一点。上例中最后的输出结果只是 0.45 在计算中的近似表示。

  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值