Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Beginner
Jun 4, 1999

Rounding function

Question:
Is there a way to round numbers to the nearest multiple of n, where n could be any number? For example, if n = 5, it would round 8 to 10, 13 to 10, 24 to 25, etc.

Answer:
There is no native function that I know about that would provide this functionality, but we could create a simple function:

Private Function RoundEx(iValue As Integer, iMod As Integer) As Integer
    If iValue Mod iMod >= iMod / 2 Then
        RoundEx = iValue + iMod - (iValue Mod iMod)
    Else
        RoundEx = iValue - (iValue Mod iMod)
    End If
End Function

Basically, we determine which way we are going to round, up or down. This is done by looking at remainder of the iValue divided by iMod. If it is greater then or equal to iMod/2 then we round up. Otherwise we round down.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date