python - 如何在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
应该工作(部分 - 总是四舍五入,见下面的评论),但想知道任何其他解决方案(只是为了好玩)?
解决方案
推荐阅读
- php - 在 PHP 中读取大于 10Gb 的视频文件大小
- sql - 在包含许多行的 SQL 表中,如何快速确定查询是否可能返回超过 1000 行
- git - 我可以追溯修复应该是“移动和更新”的“删除添加”吗?
- python - Python3 pathlib 添加额外的反斜杠 \\
- java - Android studio的设计视图为空
- python - 从多个来源使用 Web 服务并保存到 Db
- excel - 设置cookie后使用xml http请求抓取网站(Excel vba)
- javascript - 如何将 id 分配给已经附加了 Class 的按钮
- c# - C# UWP 项目中的 Linq 查询代码会根据其部件的顺序运行得更慢还是更快?
- spring - 如果从switchIfEmpty返回服务器响应,则Spring webflux“仅允许一个连接接收订阅者”