首页 > 解决方案 > 四舍五入到任何给定值python

问题描述

我有一个包含随机生成的值的列表。该列表的每个值对应于一个特定参数,如距离、时间等。我创建了一个函数,该函数将该列表的每个值四舍五入为用户输入的位数:

def round_list(list_x):
    for i in range(0, len(list_x)):
        incrementer = raw_input('Enter the increment value: ')
        list_x[i] = np.round(list_x[i], int(incrementer))
    return list_x

x = round_list(x)
print(x)

但这只会设置小数点对吗?如果用户希望它被四舍五入到 every0.25或 every0.03怎么办?我将如何整合它?我不认为round()可以做到这一点。

标签: pythonrounding

解决方案


舍入到最接近的小数值(比如 0.25)可以通过除以分数,然后舍入到最接近的整数,然后乘以分数来完成。

像这样的东西:

def roundToBase(num, base):
    return np.round(float(num) / base, 0) * base

print(roundToBase(1.3,0.25)) # 1.25

# also works for non-fractional bases,
# eg round to nearest multiple of 5:
print(roundToBase(26,5)) # 25

推荐阅读