首页 > 解决方案 > 如何在python中将整数值舍入到最接近的X倍数

问题描述

有没有一种简单的方法可以在 python 中四舍五入到最接近的 X 值?例如,要四舍五入到最接近的十位,我可以这样做:

>>> round(1845,-1)
1840

如果我想四舍五入到最近的……怎么办?

# round down when there's ambiguity
number = 1845
round(10, 1845) ==> 1840
round(5, 1845)  ==> 1845
round(2, 1845)  ==> 1844
round(50, 1845) ==> 1850
etc.

>>> round = lambda multiple, number: (number // multiple) * multiple
>>> round(1855, 10)
1850

应该工作(部分 - 总是四舍五入,见下面的评论),但想知道任何其他解决方案(只是为了好玩)?

标签: python

解决方案


推荐阅读