Automatic type conversion in Visual Basic 6.0

前端 未结 5 1538
自闭症患者
自闭症患者 2021-01-13 06:13

When we convert a float to integer in visual basic 6.0, how does it round off the fractional part? I am talkin about the automatic type conversion.

If we assign like

5条回答
  •  清酒与你
    2021-01-13 06:31

    Part of this is in the VB6 help: topic Type Conversion Functions. Unfortunately it's one of the topics that's not in the VB6 documentation on the MSDN website, but if you've installed the help with VB6, it will be there.

    When the fractional part is exactly 0.5, CInt and CLng always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2. CInt and CLng differ from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same type as is passed in.

    Implicit type coercion - a.k.a. "evil type coercion (PDF)" - from a floating point number to a whole number uses the same rounding rules as CInt and CLng. This behaviour doesn't seem to be documented anywhere in the manual.

    If you want to round up when the fractional part is >= 0.5, and down otherwise, a simple way to do it is

     n = Int(x + 0.5)
    

    And off the top of my head, here's my briefer version of Mike Spross's function which is a replacement for the VB6 Round function.

     'Function corrected, now it works. 
    Public Function RoundNumber(ByVal value As Currency, Optional PlacesAfterDecimal As Integer = 0) As Currency
      Dim nMultiplier As Long
      nMultiplier = 10 ^ PlacesAfterDecimal
      RoundNumber = Fix(0.5 * Sgn(value) + value * nMultiplier) / CDbl(nMultiplier)
    End Function
    

    Sample output:

    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'
    

提交回复
热议问题