VB6Parse / Library / Math / fix

VB6 Library Reference

Fix Function

Returns the integer portion of a number.

Syntax

Fix(number)

Parameters

Return Value

Returns the integer portion of a number: - For positive numbers: Returns the largest integer less than or equal to number - For negative numbers: Returns the first negative integer greater than or equal to number - If number is Null: Returns Null - Return type matches the input type (Integer, Long, Single, Double, Currency, Decimal)

Remarks

The Fix function truncates toward zero: - Removes the fractional part of a number - Always truncates toward zero (removes decimal without rounding) - For positive numbers, behaves like Int (same result) - For negative numbers, different from Int (Int rounds down, Fix truncates) - Fix(-8.4) returns -8, Int(-8.4) returns -9 - Fix(8.4) returns 8, Int(8.4) returns 8 - Does not round to nearest integer (use Round for rounding) - The return type preserves the input numeric type - More intuitive for most developers (truncation toward zero) - Commonly used when you want to discard fractional parts - For financial calculations, consider using Round or CCur instead

Typical Uses

  1. Truncate Decimals: Remove fractional part without rounding
  2. Integer Conversion: Convert floating-point to integer values
  3. Financial Calculations: Remove cents from currency values
  4. Data Normalization: Ensure whole number values
  5. Display Formatting: Show only whole number portion
  6. Loop Bounds: Convert float bounds to integers
  7. Array Indices: Ensure valid integer indices
  8. Coordinate Processing: Truncate pixel coordinates

Basic Usage Examples

' Example 1: Truncate positive number
Dim result As Integer
result = Fix(8.7)
Debug.Print result  ' Prints: 8
' Example 2: Truncate negative number
Dim result As Integer
result = Fix(-8.7)
Debug.Print result  ' Prints: -8 (truncates toward zero, not down)
' Example 3: Remove cents from currency
Dim price As Currency
Dim dollars As Currency
price = 19.99
dollars = Fix(price)
Debug.Print dollars  ' Prints: 19
' Example 4: Ensure integer for array index
Dim index As Long
Dim ratio As Double
ratio = 4.7
index = Fix(ratio)
value = items(index)

Common Patterns

' Pattern 1: Truncate toward zero
Function Truncate(value As Double) As Long
    Truncate = Fix(value)
End Function
' Pattern 2: Get whole dollars from currency
Function GetWholeDollars(amount As Currency) As Long
    GetWholeDollars = Fix(amount)
End Function
' Pattern 3: Get cents from currency
Function GetCents(amount As Currency) As Long
    Dim wholeDollars As Currency
    wholeDollars = Fix(amount)
    GetCents = Fix((amount - wholeDollars) * 100)
End Function
' Pattern 4: Split number into whole and fractional parts
Sub SplitNumber(value As Double, ByRef wholePart As Long, ByRef fractionalPart As Double)
    wholePart = Fix(value)
    fractionalPart = value - wholePart
End Sub
' Pattern 5: Ensure positive truncation
Function TruncatePositive(value As Double) As Long
    ' Fix truncates toward zero
    ' For negative values, this gives different result than Int
    TruncatePositive = Fix(Abs(value)) * Sgn(value)
End Function
' Pattern 6: Convert to integer without rounding
Function ToIntegerNoRound(value As Double) As Long
    ToIntegerNoRound = Fix(value)
End Function
' Pattern 7: Remove decimal places for display
Function FormatWholeNumber(value As Double) As String
    FormatWholeNumber = CStr(Fix(value))
End Function
' Pattern 8: Calculate whole units
Function GetWholeUnits(quantity As Double) As Long
    GetWholeUnits = Fix(quantity)
End Function
' Pattern 9: Truncate time to hours
Function GetWholeHours(timeValue As Double) As Long
    Dim hours As Double
    hours = timeValue * 24  ' Convert days to hours
    GetWholeHours = Fix(hours)
End Function
' Pattern 10: Floor for positive, ceiling for negative
Function TruncateTowardZero(value As Double) As Long
    ' Fix already does this
    TruncateTowardZero = Fix(value)
End Function

Advanced Usage Examples

' Example 1: Currency formatter class
Public Class CurrencyFormatter
    Public Function FormatAsDollarsAndCents(amount As Currency) As String
        Dim dollars As Long
        Dim cents As Long
        dollars = Fix(amount)
        cents = Fix(Abs((amount - dollars) * 100))
        FormatAsDollarsAndCents = "$" & dollars & "." & _
                                  Format$(cents, "00")
    End Function
    Public Function GetDollarPart(amount As Currency) As Long
        GetDollarPart = Fix(amount)
    End Function
    Public Function GetCentPart(amount As Currency) As Long
        Dim dollars As Currency
        dollars = Fix(amount)
        GetCentPart = Fix(Abs((amount - dollars) * 100))
    End Function
    Public Function RoundToDollars(amount As Currency) As Currency
        RoundToDollars = Fix(amount)
    End Function
End Class
' Example 2: Number splitter utility
Public Class NumberSplitter
    Private m_wholePart As Long
    Private m_fractionalPart As Double
    Public Sub Split(value As Double)
        m_wholePart = Fix(value)
        m_fractionalPart = value - m_wholePart
    End Sub
    Public Property Get WholePart() As Long
        WholePart = m_wholePart
    End Property
    Public Property Get FractionalPart() As Double
        FractionalPart = m_fractionalPart
    End Property
    Public Property Get HasFraction() As Boolean
        HasFraction = (m_fractionalPart <> 0)
    End Property
    Public Function Reconstruct() As Double
        Reconstruct = m_wholePart + m_fractionalPart
    End Function
End Class
' Example 3: Data truncator for normalization
Public Class DataTruncator
    Public Function TruncateArray(values() As Double) As Long()
        Dim result() As Long
        Dim i As Long
        ReDim result(LBound(values) To UBound(values))
        For i = LBound(values) To UBound(values)
            result(i) = Fix(values(i))
        Next i
        TruncateArray = result
    End Function
    Public Function TruncateToInteger(value As Double) As Long
        TruncateToInteger = Fix(value)
    End Function
    Public Function TruncateCollection(values As Collection) As Collection
        Dim result As New Collection
        Dim value As Variant
        For Each value In values
            If IsNumeric(value) Then
                result.Add Fix(CDbl(value))
            Else
                result.Add value
            End If
        Next value
        Set TruncateCollection = result
    End Function
End Class
' Example 4: Coordinate truncator
Public Class CoordinateTruncator
    Public Sub TruncatePoint(x As Double, y As Double, _
                            ByRef truncX As Long, ByRef truncY As Long)
        truncX = Fix(x)
        truncY = Fix(y)
    End Sub
    Public Function TruncateRectangle(left As Double, top As Double, _
                                      right As Double, bottom As Double) As Variant
        Dim coords(0 To 3) As Long
        coords(0) = Fix(left)
        coords(1) = Fix(top)
        coords(2) = Fix(right)
        coords(3) = Fix(bottom)
        TruncateRectangle = coords
    End Function
    Public Function GetPixelCoordinate(value As Double) As Long
        GetPixelCoordinate = Fix(value)
    End Function
End Class

Error Handling

The Fix function can raise errors or return Null: - Type Mismatch (Error 13): If number is not a numeric expression - Invalid use of Null (Error 94): If number is Null and result is assigned to non-Variant - Overflow (Error 6): If result exceeds the range of the target data type

On Error GoTo ErrorHandler
Dim result As Long
Dim value As Double
value = -12.75
result = Fix(value)
Debug.Print "Truncated value: " & result  ' Prints: -12
Exit Sub
ErrorHandler:
    MsgBox "Error in Fix: " & Err.Description, vbCritical

Performance Considerations

Best Practices

  1. Understand Difference: Know that Fix truncates toward zero, Int rounds down
  2. Negative Numbers: Be aware Fix(-8.7) = -8, Int(-8.7) = -9
  3. Currency Operations: Fix is more intuitive for removing cents
  4. Type Awareness: Be aware of return type matching input type
  5. Null Handling: Use Variant if input might be Null
  6. No Rounding: Use Round if you need rounding, not truncation
  7. Documentation: Comment when Fix vs Int choice matters

Comparison with Other Functions

Function Behavior with -8.7 Behavior with 8.7 Description
Fix -8 8 Truncates toward zero
Int -9 8 Rounds down (floor)
Round -9 9 Rounds to nearest
CLng -9 9 Converts to Long with rounding
CInt -9 9 Converts to Integer with rounding
\ N/A N/A Integer division operator

Platform and Version Notes

Limitations

← Back to Math | View all functions