As others have already pointed out, the “weird behavior” you see is due to the fact that VB6 uses Rounding Banker when rounding up fractional values.
Update 2: adding CInt does not make a difference. CInt (5.5) gives 6 and Cint (8.5) gives 8!
This is also normal. CInt always rounds before performing the conversion (again using the Banker rounding method).
If you have a number with a fractional part and just want to truncate it (ignore the part after the decimal point), you can use either the Fix or Int function:
Fix(1.5) = 1 Fix(300.4) = 300 Fix(-12.394) = -12
Int works just like Fix , except that it rounds negative numbers to the next lower negative number:
Int(1.5) = 1 Int(300.4) = 300 Int(-12.394) = -13
If you really want to round the number according to the rules that most people are familiar with, you will have to write your own function to do this. The following is an example of rounding, which is rounded when the fractional part is greater than or equal to 0.5, and rounded otherwise:
EDIT : See MarkJ's answer for a simpler (and probably faster) version of this function.
' Rounds value to the specified number of places' ' Probably could be optimized. I just wrote it off the top of my head,' ' but it seems to work.' Public Function RoundNumber(ByVal value As Double, Optional PlacesAfterDecimal As Integer = 0) As Double Dim expandedValue As Double Dim returnValue As Double Dim bRoundUp As Boolean expandedValue = value expandedValue = expandedValue * 10 ^ (PlacesAfterDecimal + 1) expandedValue = Fix(expandedValue) bRoundUp = (Abs(expandedValue) Mod 10) >= 5 If bRoundUp Then expandedValue = (Fix(expandedValue / 10) + Sgn(value)) * 10 Else expandedValue = Fix(expandedValue / 10) * 10 End If returnValue = expandedValue / 10 ^ (PlacesAfterDecimal + 1) RoundNumber = returnValue End Function
<strong> Examples
Debug.Print RoundNumber(1.6) '2' Debug.Print RoundNumber(-4.8) '-5' Debug.Print RoundNumber(101.7) '102' Debug.Print RoundNumber(12.535, 2) '12.54'
source share