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.
Easy Java Solution:
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
With using cmath::abs
int rounded = n + abs((n % denom) - denom);
You can change denom
with any denomination you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.