A better rounding function

VB's built in round function will round numbers like 12.085 down to 12.08. This is not correct in all cases as this number should be rounded up to 12.09. This round function allows for this.

Public Function RoundAdv(ByVal dVal As Double, Optional ByVal iPrecision As Integer = 0) As Double
       Dim roundStr As String
       Dim WholeNumberPart As String
       Dim DecimalPart As String
       Dim i As Integer
       Dim RoundUpValue As Double
       roundStr = CStr(dVal)
       If InStr(1, roundStr, ".") = -1 Then
           RoundAdv = dVal
           Exit Function
       End If
       WholeNumberPart = Mid$(roundStr, 1, InStr(1, roundStr, ".") - 1)
       DecimalPart = Mid$(roundStr, (InStr(1, roundStr, ".")))
       If Len(DecimalPart) > iPrecision + 1 Then
           Select Case Mid$(DecimalPart, iPrecision + 2, 1)
               Case "0", "1", "2", "3", "4"
                   DecimalPart = Mid$(DecimalPart, 1, iPrecision + 1)
               Case "5", "6", "7", "8", "9"
                   RoundUpValue = 0.1
                   For i = 1 To iPrecision - 1
                       RoundUpValue = RoundUpValue * 0.1
                   DecimalPart = CStr(Val(Mid$(DecimalPart, 1, iPrecision + 1)) + RoundUpValue)
                   If Mid$(DecimalPart, 1, 1) <> "1" Then
                       DecimalPart = Mid$(DecimalPart, 2)
                       WholeNumberPart = CStr(Val(WholeNumberPart) + 1)
                       DecimalPart = ""
                   End If
           End Select
       End If
       RoundAdv = Val(WholeNumberPart & DecimalPart)

   End Function

You might also like...


Luke Lesurf Erm I went to school, then college and then i got a job... In programming. I like to fly planes and go fishing. I dont like brussle sprouts or cabbage. Love walker's squares. And coke (as in cola)


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” - Brian Kernighan