Rounding Code

wllsth

Registered User.
Local time
Today, 09:29
Joined
Sep 17, 2008
Messages
81
I am using the following bit of code which I picked up from a forum and it works fine except were I present it with an amount of 13.00 or 14.00 basically anything with 00 after the decimal point. Any clues how to get rid of the error !!

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
Next
DecimalPart = CStr(Val(Mid$(DecimalPart, 1, iPrecision + 1)) + RoundUpValue)
If Mid$(DecimalPart, 1, 1) <> "1" Then
DecimalPart = Mid$(DecimalPart, 2)
Else
WholeNumberPart = CStr(Val(WholeNumberPart) + 1)
DecimalPart = ""
End If
End Select
End If
RoundAdv = Val(WholeNumberPart & DecimalPart)
End Function
 
The Code at the beginning needs correction:
Code:
If InStr(1, roundStr, ".") = -1 Then
       RoundAdv = dVal
Exit Function
End If
must be written as:
Code:
If InStr(1, roundStr, ".") = 0 Then
       RoundAdv = dVal
Exit Function
End If

The result of the InStr() test will be a number >0 if a match "." found in the String or it will be 0, Never -1.

I didn't go through the entire length of the Code, but why we need so much code for a simple Round Function. Can't we write something like:

Code:
Public Function RoundAdv(Byval dVal as Double, Optional byval iprecision as integer=0) as Double
   RoundAdv = INT(dVal * 10^iprecision + 0.5)/10^iprecision
End Function
 
You could use the built-in ROUND function....

Round (Number value, Number of decimal places to round to)

if the second parameter is set to 0 it will round to the interger, if 1 is used, it will round to the nearest tenth..ect
 

Users who are viewing this thread

Back
Top Bottom