在 Python 中四舍五入到 5(或其他数字)

新手上路,请多包涵

是否有内置函数可以像下面这样舍入?

 10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20

原文由 Pydev UA 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 541
2 个回答

我不知道 Python 中的标准函数,但这对我有用:

蟒蛇3

 def myround(x, base=5):
    return base * round(x/base)

很容易看出为什么上面的方法有效。你想确保你的数字除以 5 是一个正确四舍五入的整数。所以,我们首先这样做( round(x/5) ),然后因为我们除以 5,所以我们也乘以 5。

我通过给它一个 base 参数使函数更通用,默认为 5。

蟒蛇2

In Python 2, float(x) would be needed to ensure that / does floating-point division, and a final conversion to int is needed because round() 在 Python 2 中返回一个浮点值。

 def myround(x, base=5):
    return int(base * round(float(x)/base))

原文由 Alok Singhal 发布,翻译遵循 CC BY-SA 4.0 许可协议

舍入为非整数值,例如 0.05:

 def myround(x, prec=2, base=.05):
  return round(base * round(float(x)/base),prec)

我发现这很有用,因为我只需搜索并替换我的代码即可将“round(”更改为“myround(”,而无需更改参数值。

原文由 CCKx 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题