Round a number to a multiple of another number






3.14/5 (14 votes)
Code to round a number to the nearest multiple of another number.
Introduction
While developing an application for our purchase department, I came across a small problem that I could not find any ready made code samples for. Rounding a number up or down is real easy as long as you are talking about number of decimals and/or if you always want to round up or always down. Our purchaser wanted my application to suggest an amount of items to order, rounded up or down to the nearest multiple of the number of items per box.
After writing and abandoning many, many, many lines of code, I finally resorted back to the K.I.S.S. principle and wrote a small function that can easily be inserted anywhere in existing code. I suppose it is not something many people will ever need, but considering how long it took me to figure this one out, I can imagine that I will make at least a few people happy with a ready made solution.
The code
Here is the code, just insert it anywhere in your application, and call it as you see fit. Feed it the number you want rounded and the significance you want it rounded to. The function then returns an integer value that is the closest multiple of the significance to the number:
Public Function RoundToSignificance(ByVal number As Integer, _
ByVal significance As Integer) As Integer
'Round number up or down to the nearest multiple of significance'
Dim d As Double
d = number / significance
d = Round(d, 0)
RoundToSignificance = d * significance
End Function
Final note
The function as is needs two integer values and returns an integer value, but I guess it can easily be adapted to accept and/or return some other type. As a beginner, I can also imagine that there may actually be some existing function or method, but I couldn't find it. If anyone knows of a simpler way to do what this little function does, please let me know.