VB and VBA Users Source Code: Rounding a variable to a specified number of decimal places
[
Home
|
Contents
|
Search
|
Reply
|
Previous
| Next ]
VB/VBA Source Code
Rounding a variable to a specified number of decimal places
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Friday, December 15, 2000
Hits:
795
Category:
Office
Article:
'Purpose : Performs arithmetic rounding (rather than an accountancy round (as per the Round function)) 'Inputs : fNumber The number to round ' [lDecimalPlaces] The number of DP to round to. 'Outputs : Returns a rounded number 'Author : Andrew Baker 'Date : 15/01/2001 22:34 'Notes : Rounds to a max of +50 or -50 DP. 'Revisions : Public Static Function RoundToDP(fNumber As Double, Optional ByVal lDecimalPlaces As Long) As Double Dim i As Long Dim fTmp As Double Dim afPower10(-50 To 50) As Double On Error Goto ErrFailed If i = 0 Then '(all vars are static) afPower10(0) = 1# For i = 1 To UBound(afPower10) afPower10(i) = afPower10(i - 1) * 10# afPower10(-i) = afPower10(1 - i) / 10# Next End If If fNumber >= 0 Then fTmp = fNumber * afPower10(lDecimalPlaces) + 0.5 RoundToDP = Int(fTmp) * afPower10(-lDecimalPlaces) Else fTmp = -fNumber * afPower10(lDecimalPlaces) + 0.5 RoundToDP = -Int(fTmp) * afPower10(-lDecimalPlaces) End If Exit Function ErrFailed: Debug.Print err.description Debug.Assert False Exit Function Resume End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder