四舍五入到任何给定值python

时间:2018-05-30 09:40:57

标签: python rounding

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

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)

但是这只能设置小数点吗? 如果用户希望将其四舍五入到每0.25或每0.03,该怎么办? 我该如何加入?我认为round()无法做到这一点。

2 个答案:

答案 0 :(得分:1)

舍入到最近的小数值(比如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

答案 1 :(得分:0)

试试这个:

def round(number, nearest):

    if ((number % nearest) / nearest) < 0.5:
        return (number - (number % nearest))
    else:
        return ((number - (number % nearest)) + nearest)

说明:

if检查nearest的数量与最前一个倍数之间的差异是否小于nearest的一半。如果是,则表示该数字需要向下舍入,这就是为什么,如果它是True,则返回nearest的最前一个倍数。如果是False,则返回(nearest的最后一个倍数)+ nearest

相关问题