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!