四舍五入到最接近的整数倍 [英] Round to nearest multiple of a number

查看:196
本文介绍了四舍五入到最接近的整数倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种惯用的方法将数字四舍五入到最近的数,而不能上下四舍五入并查看哪一个是最接近的?

Is there an idiomatic way to round to the nearest multiple of a number, short of rounding both up and down and seeing which one is closest?

仅假定整数:

number   multiple   result
12       5          10
13       5          15
149      10         150

推荐答案

加倍数的一半,然后向下舍入.

Add half of the multiple, then round down.

result = ((number + multiple/2) / multiple) * multiple;

result = number + multiple/2;
result -= result % multiple;

如果数字恰好在中间,则四舍五入.如果您希望在这种情况下有不同的行为,则可能需要调整计算.另外,请注意如果number可能在类型范围的顶部附近.

This rounds up if the number is exactly in the middle. You might need to tweak the calculation if you want different behaviour in that case. Also, beware overflow if number might be near the top of the type's range.

这篇关于四舍五入到最接近的整数倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆