RoundUp and RoundDown Functions in VB.NET


There are two very important functions that VB.NET lacks, they are : RoundUp and RoundDown functions. these two important functions are not readily available for use and as such, i have included both the functions here for you to play with.
Just copy & paste the codes below anywhere into your VB.NET projects and you are ready to access RoundUp and RoundDown functions. With these functions, rounding in Visual Basic has never been easier!
Happy Programming!




Public Function RoundUp(ByVal InputVal As Double) As Double
' Round Up Function
Try
Dim Deci As Long = InStr(1, CStr(InputVal), ".", CompareMethod.Text)
If Deci > 0 Then
Return (CDbl(Mid(CStr(InputVal), 1, Deci)) + 1)
Else
Return (InputVal)
End If
Catch
MsgBox(Err.Description, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "RoundUp Error")
End Try
End Function




Public Function RoundDown(ByVal InputVal As Double) As Double
' Round Down Function
Try
Dim Deci As Long = InStr(1, CStr(InputVal), ".", CompareMethod.Text)
If Deci > 0 Then
Return (CDbl(Mid(CStr(InputVal), 1, Deci)))
Else
Return (InputVal)
End If
Catch
MsgBox(Err.Description, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "RoundDown Error")
End Try
End Function



Back to VB Egg

3 comments

  1. Anonymous // Saturday, December 06, 2008 8:13:00 PM  

    In This line "Return (CDbl(Left(CStr(InputVal), Deci)))"

    The "Left" has a line under it and says

    "Public Property Left() As Integer' has no parameters and its return type cannot be indexed."

    have i done something wrong to make it say that?

  2. Anonymous // Sunday, December 07, 2008 5:55:00 AM  

    well in the end i just used "Fix" & "single" to round down

    Dim divison10 As Single
    divison10 = userCash / price10
    nudQty10.Maximum = Fix(divison10)

  3. Fluffy // Sunday, January 04, 2009 6:20:00 AM  

    Sorry for the error that you encountered with the code that i have provided. VB.NET no longer supports the Left() and Right() function anymore which is widely used during the time of Visual Basic 6 or VB Classic. They are now replaced with Mid() function instead. They are practically similar, all you have to do is just replace the line "Return (CDbl(Left(CStr(InputVal), Deci)))" with Return (CDbl(Mid(CStr(InputVal), 1, Deci))). I have already made the necessary corrections in the code though. Anyway, thanks for your comments.