VB and VBA Users Source Code: Mathematical Rounding Function (always rounds 0.5 correctly)
[
Home
|
Contents
|
Search
|
Reply
| Previous |
Next
]
VB/VBA Source Code
Mathematical Rounding Function (always rounds 0.5 correctly)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Sunday, June 25, 2000
Hits:
1064
Category:
Office
Article:
The VB6 "Round" function rounds .5 down when the integer portion is even and up when it's odd. This is designed for statistical applications, where on average you will round up half the time and down half the time. However, most other applications always want 0.5 to round up. The following function performs this "mathematical" round. 'Purpose : Returns a mathematically rounded number. 'Inputs : lhwndListview The handle to the listview (eg. Listview1.Hwnd) 'Outputs : Returns a count on the number of selected items. 'Author : Andrew Baker 'Date : 23/07/2000 18:52 'Notes : VB's round function performs a statistical round. Example: ' Round(4.5,0) = 4 ' RoundMath(4.5,0) = 5 'Revisions : Function RoundMath(ByVal vNumberToRound As Variant, Optional iDecimalPlaces As Integer) As Double Dim iDP As Integer If iDecimalPlaces Then vNumberToRound = vNumberToRound * 10 ^ iDecimalPlaces iDP = CInt(10 * (vNumberToRound - Int(vNumberToRound))) If iDP > 4 Then 'Round up RoundMath = CDbl(Int(vNumberToRound) + 1) Else 'Round down RoundMath = CDbl(Int(vNumberToRound)) End If RoundMath = RoundMath / 10 ^ iDecimalPlaces Else iDP = CInt(10 * (vNumberToRound - Int(vNumberToRound))) If iDP > 4 Then 'Round up RoundMath = CDbl(Int(vNumberToRound) + 1) Else 'Round down RoundMath = CDbl(Int(vNumberToRound)) End If End If End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder