Python中字典列表整数按指定精度向上/向下/四舍五入实现方法
Python按指定位数取整的极简实现方案
核心逻辑
所有按十位、百位、千位等精度的取整操作,都可以通过「先除以10的N次方(N为精度位数,十位为1、百位为2、千位为3,以此类推)→ 做取整运算 → 再乘回10的N次方」的逻辑实现,代码简洁且兼容Python2.7+所有版本,无需额外依赖。
参数说明:
num:待处理的整数digits:指定精度位数,十位传1、百位传2、千位传3,以此类推
三种取整实现
1. 向上取整(匹配你的需求示例)
import math def round_up(num, digits): factor = 10 ** digits return math.ceil(num / factor) * factor
测试效果:
round_up(13, 1)→ 20round_up(2237, 1)→ 2240round_up(3451, 2)→ 3500
2. 向下取整
import math def round_down(num, digits): factor = 10 ** digits return math.floor(num / factor) * factor
测试效果:
round_down(2312, 1)→ 2310round_down(467, 2)→ 400
3. 标准四舍五入(0-4舍去、5-9进1,规避Python内置round的银行家舍入问题)
def round_standard(num, digits): factor = 10 ** digits return int(num + factor / 2) // factor * factor
测试效果:
round_standard(14, 1)→ 10round_standard(15, 1)→ 20
你的场景实际运行代码
import math def round_up(num, digits): factor = 10 ** digits return math.ceil(num / factor) * factor # 原始数据 data = {'Key':[2312, 467]} # 按十位精度向上取整处理 data['Key'] = [round_up(x, 1) for x in data['Key']] print(data) # 输出结果:{'Key': [2320, 470]},完全符合预期
内容的提问来源于stack exchange,提问作者Justme4ever
相关产品推荐
相关产品推荐

