PRB: Type Conversion Functions Can Return Unexpected Results (195657)
The information in this article applies to:
- Microsoft Visual Basic Learning Edition for Windows 5.0
- Microsoft Visual Basic Learning Edition for Windows 6.0
- Microsoft Visual Basic Professional Edition for Windows 5.0
- Microsoft Visual Basic Professional Edition for Windows 6.0
- Microsoft Visual Basic Enterprise Edition for Windows 5.0
- Microsoft Visual Basic Enterprise Edition for Windows 6.0
- Microsoft Visual Basic Standard Edition, 32-bit, for Windows 4.0
- Microsoft Visual Basic Professional Edition, 16-bit, for Windows 4.0
- Microsoft Visual Basic Professional Edition, 32-bit, for Windows 4.0
- Microsoft Visual Basic Enterprise Edition, 16-bit, for Windows 4.0
- Microsoft Visual Basic Enterprise Edition, 32-bit, for Windows 4.0
This article was previously published under Q195657 SYMPTOMS
Type conversion functions, such as CInt, may sometimes return unexpected
results. For example, CInt(2.5) should return 2 according to the
documentation. However, CInt(25.0 * 0.1) will sometimes result in 3.
CAUSE
This is caused by the way floating point values are handled in computers.
Because most floating point values cannot be accurately represented with
fixed length binary values, the internal result of the floating point
calculation may differ slightly. For example, 25.0 * 0.1 may be 02.5000...
001 or 02.4999...999 depending on many factors. This rounding error causes
the CInt function to return 2 or 3 in different situations.
RESOLUTION
This is expected behavior and there is no fix for this. However, you can
make these functions return the expected values more often by using
wrapping functions. For example, you can use the following function instead
of using CInt:
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.
STATUS
This behavior is by design.
REFERENCES
For more information regarding precision and accuracy in floating point
calculations, please see the following articles in the Microsoft Knowledge
Base:
125056 INFO: Precision and Accuracy in Floating-Point Calculations
145889 INFO: Why Floating Point Numbers May Lose Precision
Modification Type: | Major | Last Reviewed: | 6/24/2004 |
---|
Keywords: | kbcode kbFloatPoint kbprb KB195657 |
---|
|