Article ID: 195657
Article Last Modified on 6/24/2004
Private Function MyCInt(ByVal dTemp As Double) As Integer
MyCInt = CInt(dTemp)
End Function
This works by forcing the expression to be evaluated and stored into an
intermediate variable. This forces rounding, which often discards the small
difference between the correct value and the real value in the computer.
This method can also be used for CLng, etc.
Option Explicit
Private Function MyCInt(Byval dTemp As Double) As Integer
MyCInt = CInt(dTemp)
End Function
Private Sub Command1_Click()
Dim t As Single, s As Single
Dim z As Integer, h As Integer
Dim Msg As String
Msg = "Using CInt for these calculations:" & vbCrLf
t = 25#
s = t * 0.1
Msg = Msg & "The result of 25.0 * 0.1 = " & s & vbCrLf
h = CInt(s)
Msg = Msg & "Where t = 25#, and s = t * 0.1, the result of " _
& "CInt(t * 0.1) = " & h & vbCrLf
z = CInt(t * 0.1)
Msg = Msg & "And the result of CInt(t * 0.1) = " & z
MsgBox Msg
End Sub
Private Sub Command2_Click()
Dim t As Single, s As Single
Dim z As Integer, h As Integer
Dim Msg As String
Msg = "Using MyCInt for these calculations:" & vbCrLf
t = 25#
s = t * 0.1
Msg = Msg & "The result of 25.0 * 0.1 = " & s & vbCrLf
h = MyCInt(s)
Msg = Msg & "Where t = 25#, and s = t * 0.1, the result of " _
& "MyCInt(t * 0.1) = " & h & vbCrLf
z = MyCInt(t * 0.1)
Msg = Msg & "And the result of MyCInt(t * 0.1) = " & z
MsgBox Msg
End Sub
125056 INFO: Precision and Accuracy in Floating-Point Calculations
145889 INFO: Why Floating Point Numbers May Lose Precision
Keywords: kbprb kbfloatpoint kbcode KB195657