python中取整数操作

python中取整数操作

★向靠近零的方向取整

int(x)内置函数【https://docs.python.org/zh-cn/3/library/functions.html#int 】,向靠近零的方向取整,x是数字表达式,如

int(4.4)  #得到4

int(-4.4)  #得到-4

int(4.5)  #得到4

int(-4.5)  #得到-4

int(4.6)  #得到4

int(-4.6)  #得到-4

★靠近上限取整——大于或等于的最小的整数

math模块中的ceil(x)函数,返回大于或等于 x 的最小的整数,注意,需要导入标准(内置)math模块。【math模块https://docs.python.org/zh-cn/3/library/math.html

import math #导入 math

math.ceil(4.4)  #得到5

math.ceil(-4.4)  #得到-4

math.ceil(4.5) #得到5

math.ceil(-4.5)  #得到-4

math.ceil(4.6)  #得到5

math.ceil(-4.6)  #得到-4

★靠近下限取整——小于或等于的最大整数

math模块中的floor(x)函数,返回小于或等于 x 的最大整数。

import math #导入 math

math. floor (4.4)  #得到4

math. floor (-4.4)  #得到-5

math. floor (-4.5) #得到-5

math. floor (4.6)  #得到4

math. floor (-4.6)  #得到-5

★内置函数round(number [, digits])

参数         描述

number    必需。要舍入的数字。

digits        可选。四舍五入时要使用的小数位数。默认为 0。

https://docs.python.org/zh-cn/3/library/functions.html#round

特别注意python中,此函数的舍入规则不是传统意义上的四舍五入,原因是有如下情况:

round(2.665, 2)  #得到2.67

round(2.675, 2)  #得到2.67

round(2.5) #得到2

round(-2.5) #得到-2

round(3.5) #得到4

round(-3.5) #得到-4

在Python中如何四舍五入

可以自定义个函数用,需要导入标准(内置) decimal模块【https://docs.python.org/zh-cn/3/library/decimal.html 】,下面给出自定义四舍五入函数源码:

from decimal import Decimal,ROUND_HALF_UP
def round2(num,keep_n=0):
    #num是转换的数,keep_n是保留位数,默认0位
    if isinstance(num,float):
        num = str(num)
    return Decimal(num).quantize((Decimal('0.' + '0'*keep_n)),rounding=ROUND_HALF_UP)

#下面是调用自定义函数round2()
print(round2(2.665, 2))  #得到2.67
print(round2(2.675, 2))  #得到2.68
print(round2(2.5)) #得到3
print(round2(-2.5)) #得到-3
print(round2(3.5)) #得到4
print(round2(-3.5)) #得到-4

print(round2(3.4))  #得到3
print(round2(-3.4))  #得到-3
print(round2(3.6)) #得到4
print(round2(-3.6)) #得到-4

运行效果:

OK!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习&实践爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值