|
|
Title | Round a number to the nearest multiple of a template in Visual Basic 6 |
Description | This example shows how to round a number to the nearest multiple of a template in Visual Basic 6. |
Keywords | round, round off, digits, Visual Basic 6, template |
Categories | Algorithms |
|
|
Thanks to Randy Diven.
The RoundToTemplate function divides a value by a template number, rounds the result, and then multiplies this by the template number.
|
|
Public Function RoundToTemplate(ByVal value As Double, _
ByVal template As Double) As Double
Debug.Assert template > 0.0000000001
RoundToTemplate = template * Round(value / template, 0)
End Function
|
|
The result is the multiple of the template closest to the original value.
If the template number is something "reasonable" such as 5, 25 or a power of 10, the result makes good intuitive sense. If the template number is something less intuitive, such as 17 or 33, the result is less obvious.
Here are some sample results:
|
|
value template RoundtoTemplate
123.08875 25 125
20 120
0.01 123.09
0.05 123.10
17.17 120.19
7 126
|
|
|
|
|
|