简体   繁体   English

四舍五入到最接近的数字倍数

[英]Round to nearest multiple of a number

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?是否有一种惯用的方法可以四舍五入到数字的最接近倍数,而不是向上和向下四舍五入并查看哪个最接近?

Assume only integers:假设只有整数:

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;

or或者

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

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.此外,如果number可能接近类型范围的顶部,请注意溢出。

Easy Java Solution:易 Java 解决方法:

public Long roundToNearestLong(Long number, Long multiple) {
        if (number == null)
            return 0L;

        Long smallerMultiple = (number / multiple) * multiple;
        Long largerMultiple = smallerMultiple + multiple;

        // Return of closest of two
        return (number - smallerMultiple >= largerMultiple - number) ? largerMultiple : smallerMultiple;
    }

Mike Seymour的答案假设“数字”为正

I've answered this before on Rounding off a number to the next nearest multiple of 5我之前在将数字四舍五入到下一个最接近的 5 的倍数上回答了这个问题

With using cmath::abs使用cmath::abs

int rounded = n + abs((n % denom) - denom);

You can change denom with any denomination you want你可以改变denom你想要的任何面值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM