python将数字舍入到特定值

时间:2021-07-07 09:18:39

标签: python numpy math rounding ceil

我想写一个特定的舍入逻辑。

number = x

if x < 950:
    # round number to and in steps of 50
elif x < 9000:
    # round number to and in steps of 100
elif x < 100000:
    # round number to and in steps of 250
else:
    # round number to and in steps of 1000

这是我的想法,它是如何工作的。

例如,我需要什么,如果 x = 123,那么它应该四舍五入为 100。 如果 x = 170 它应该四舍五入到 200,然后例如对于 x = 8568 它应该四舍五入到 8600

2 个答案:

答案 0 :(得分:3)

很可能不是最干净的方法,但是: (x + step/2)//step*step 应该可以工作。

示例: print((880+25)//50*50) 返回 900

答案 1 :(得分:-2)

回顾后,第一种技术仅适用于 10 的幂: def四舍五入(重要数字,数字): x = 数字/(10 **重要数字) 加 = 1 对于我在 str(x).split(".")[1] : 我 = 整数(i) 如果我 < 5 : 加 = 0 休息 如果我 > 5 : 加 = 1 休息 返回 (int(x) + plus) * 10 **重要数字

或者更容易:

round(x/value)*value

相关问题