VB and VBA Users Source Code: Rounding a number to the nearest lot size
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Rounding a number to the nearest lot size
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Friday, July 28, 2006
Hits:
3608
Category:
Visual Basic General
Article:
The code below rounds numbers so that the are exactly divisible by another number, ie rounding to the nearest lotsize. 'Purpose : Rounds a number rounded so that it is exactly divisable by a specified number. 'Inputs : fNumber The number to round. ' fToNearest The amount to round to. 'Outputs : Returns the number which is closest to fNumber and exactly divisible fRoundToNearest. 'Author : Andrew Baker 'Date : 13/11/2002 10:16 'Examples : Expression: Result: ' RoundToNearest(12, 5) 10 ' RoundToNearest(12, 6) 12 ' RoundToNearest(105, 5) 105 ' RoundToNearest(105, 10) 100 'Revisions : Public Function RoundToNearest(fNumber As Double, fToNearest As Double) As Long Dim fMod As Double fMod = fNumber Mod fToNearest If fMod <> 0 Then If fMod < (fToNearest / 2) Then 'Round down RoundToNearest = fNumber - fMod Else 'Round up RoundToNearest = (fNumber - fMod) + fToNearest End If Else RoundToNearest = fNumber End If End Function 'Demonstration code Sub test() Debug.Print RoundToNearest(101, 5) 'Returns 100 Debug.Print RoundToNearest(104, 5) 'Returns 105 Debug.Print RoundToNearest(105, 5) 'Returns 105 Debug.Print RoundToNearest(106, 5) 'Returns 105 Debug.Print RoundToNearest(109, 5) 'Returns 110 End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder