1 前言
在Python中,常用的保留整数的方式有三种:截断取整、四舍五入和向上/向下取整。以下是每种方式的详细介绍及对比
1.1 截断取整【int()函数】
功能:直接截断小数部分,保留整数部分。不进行任何舍入
适用场景
- 需要快速获取浮点数的整数部分,忽略小数部分
- 例如:统计物品数量(如29.9个苹果视为29个)
1.2 四舍五入【round()函数】
语法:round(x [, n])
作用:根据小数部分进行四舍五入
参数
- x -- 浮点数
- n -- 可选,保留的小数点位数。如果不写的话,默认保留到整数
功能:根据小数部分进行四舍五入
TIPS:但是round()函数使用“银行家舍入法”(四舍六入五成双)。即:当小数部分为0.5时,会向最近的 偶数 取整
适用场景
- 需要符合数学四舍五入规则的计算
- 例如:成绩计算(89.5分视为90分)
PS:但是会有一个问题,如果是88.5的话,会计算成88,所以round也不是严格意义的四舍五入。那怎么解决呢?在最后我会进行讲解
1.3 向上/向下取整【math.ceil()和math.floor()】
功能
- math.ceil():向上取整,无论小数部分多小,均进位到下一个整数
- math.floor():向下取整,无论小数部分多大,均舍去小数部分
适用场景
- 需要明确向上或向下取整的操作
- 例如:计算物流箱数(29.1公斤货物需要30个箱子)
2 代码示例
import math
# 截断取整
print(int(29.9)) # 输出: 29
print(int(-29.9)) # 输出: -29
# 四舍五入
print(round(28.5)) # 输出:28
print(round(29.5)) # 输出: 30
print(round(-29.5)) # 输出: -30
# 向上取整
print(math.ceil(29.1)) # 输出: 30
print(math.ceil(-29.1)) # 输出: -29
# 向下取整
print(math.floor(29.9)) # 输出: 29
print(math.floor(-29.9))# 输出: -30
3 选择建议
- 若需简单截断,用int()
- 若需四舍五入,用round()
- 若需向上/向下取整,用math.ceil()或math.floor()
4 最后
如果我需要严格的四舍五入,即:将浮点数转换为整数,应该怎么办呢?
方法:使用int(),自定义函数
示例
"""
type1: float -> int
功能: 实现浮点数到整数,精确的四舍五入
"""
def strict_round(x):
integer = int(x + 0.5) if x >= 0 else int(x - 0.5)
return integer
# 测试
print(strict_round(28.5)) # 输出 29
print(strict_round(29.5)) # 输出 30
print(strict_round(28.4)) # 输出 28
print(strict_round(20)) # 输出 20
2025年3月25日-补充
上述代码只能实现浮点数 -> 整数的四舍五入,无法实现动态的精确位数,所以我对上述代码进行了优化,可以根据自己的需求,保留小数点后n位,如下所示
"""
type2: float -> int or float
功能: 实现浮点数,精确的四舍五入,保留指定位数(默认保留0位)
"""
def strict_round(x, ndigits=0):
factor = 10 ** ndigits
scaled = x * factor
rounded_value = int(scaled + 0.5) if scaled >= 0 else int(scaled - 0.5)
result = rounded_value if ndigits == 0 else rounded_value / factor
return result
# 测试
user_input = input("请输入浮点数和精确位数(用空格分隔): ").split()
input_num = float(user_input[0]) # 第一个元素转为浮点数
ndigits = int(user_input[1]) # 第二个元素转为整数
# 调用函数并打印结果
x = strict_round(input_num, ndigits)
print(f"x:{x}, type: {type(x)}")
以上实例,执行输出结果为:
请输入浮点数和精确位数(用空格分隔): 2.4789415664849 0
x:2, type: <class 'int'>
请输入浮点数和精确位数(用空格分隔): 2.46949844196859 5
x:2.4695, type: <class 'float'>