Round to the Nearest Multiple of 5

I needed a code snippet that can get the nearest multiple of 5 based on a number.

For example, 11 should be 15, 16 should be 20, 26 should be 30 and so forth.

11 -> 15
16 -> 20
26 -> 30

Here is the way to think about this problem. So the final result should be multiple of 5, so if the original number is divided by 5, the remainder should be 0, 1, 2, 3 or 4. If you divide 11 by 5, the remainder is 4. If you add this 4 to 11, you get the nearest multiple of 5. So to generalize this to an equation…

original_num = 11
result = original_num + original_num % 5

It’s really easy when you think about it, but if you have not gone through a problem like this before, maybe it’s hard to come up with the idea to use remainder.

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *