Code Snippets

  

Visual Basic Source Code


Welcome to Dream.In.Code
Become a VB Expert!

Join 148,918 VB Programmers for FREE! Get instant access to thousands of VB experts, tutorials, code snippets, and more! There are 2,434 people online right now. Registration is fast and FREE... Join Now!





RoundUp and RoundDown functions in VB 6.0

Two simple functions that are not found in VB. Suppose you have a number '3.376'. Now when you will use the RoundUp function you will get the result as '4.0'. By using RoundDown function the result would be '3.0'. However, for .NET you could use the Math.Floor and Math.Ceiling methods

Submitted By: irtaza
Actions:
Rating:
Views: 37,120

Language: Visual Basic

Last Modified: April 14, 2005

Snippet


  1. Public Function roundDown(dblValue As Double) As Double
  2. On Error GoTo PROC_ERR
  3. Dim myDec As Long
  4.  
  5. myDec = InStr(1, CStr(dblValue), ".", vbTextCompare)
  6. If myDec > 0 Then
  7.     roundDown = CDbl(Left(CStr(dblValue), myDec))
  8. Else
  9.     roundDown = dblValue
  10. End If
  11.  
  12. PROC_EXIT:
  13.     Exit Function
  14. PROC_ERR:
  15.     MsgBox Err.Description, vbInformation, "Round Down"
  16. End Function
  17.  
  18. Public Function roundUp(dblValue As Double) As Double
  19. On Error GoTo PROC_ERR
  20. Dim myDec As Long
  21.  
  22. myDec = InStr(1, CStr(dblValue), ".", vbTextCompare)
  23. If myDec > 0 Then
  24.     roundUp = CDbl(Left(CStr(dblValue), myDec)) + 1
  25. Else
  26.     roundUp = dblValue
  27. End If
  28.  
  29. PROC_EXIT:
  30.     Exit Function
  31. PROC_ERR:
  32.     MsgBox Err.Description, vbInformation, "Round Up"
  33. End Function
  34.  

Copy & Paste


Comments


MikoMia 2008-01-09 02:52:05

*O*M*G* Ever heard of the build in Int function?! To Round Down, use Int(), as in: Dim n as Double, floor as Double n = 3.99745823 floor = Int(n) To Round Up, simply use If Int(number)number Then ceil = Int(number) + 1 Else ceil = number End If oh.. and this code is about 1000x faster..

Mordy 2008-09-08 08:39:11

Won't anything from 3.50 to 3.99 be rounded up to 4 if you use the built-in INT function? I think that's why he made this function.

AndyEsser 2008-11-04 10:06:27

You have a problem with this function if you start having numbers so small they start getting displayed as standard form, ie 1.66e-2 since it checks for the decimal point and does go by the value.

richmassena 2008-12-22 12:04:26

you really must be joking. Parsing the string representation of a number to round it up. Try something like this: newnumber=int(number+.5)


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live VB Help!

VB Tutorials

Reference Sheets

VB Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month