'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
Solution 1:[1]
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.
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | siddhartha agarwal |
