Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleRound a number to the nearest multiple of a template in Visual Basic 6
DescriptionThis example shows how to round a number to the nearest multiple of a template in Visual Basic 6.
Keywordsround, round off, digits, Visual Basic 6, template
CategoriesAlgorithms
 
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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated