If anyone can improve it, feel free, and please post your improved function this thread.
Code:
Private Function FormatNumber(Expression As String, _
Optional NumDigitsAfterDecimal As Integer, Optional IncludeLeadingDigit As Boolean, _
Optional UseParensForNegativeNumbers As Boolean, Optional GroupDigits As Boolean) As String
'NOTE: Param Expression is defined as Object in VB6
'VB5 Implementation for VB6 equivalent
Const kPound As String = "#"
Const kZero As String = "0"
Const kPeriod As String = "."
Const kComma As String = ","
Dim blnIsFloat As Boolean
Dim i As Integer
Dim iLen As Integer
Dim iPos As Integer
Dim strFormat As String
Dim sLeft As String
Dim sRight As String
'Check for Period in Expression
iPos = InStr(1, Expression, kPeriod)
If iPos > 0 Then blnIsFloat = True
If Not blnIsFloat Then
'Expression is Integer or Long
'Rare for leading 0 so just use #
For i = 0 To Len(Expression)
strFormat = strFormat & kPound
Next
End If
'--------------------------------
'Leading Zero
'Use All Zeros instead of # signs
'--------------------------------
If IncludeLeadingDigit Then
If blnIsFloat Then
For i = 0 To iPos - 1
strFormat = strFormat & kZero
Next
Else
strFormat = kZero & Right$(strFormat, Len(strFormat) - 1)
End If
Else
If blnIsFloat Then
'No leading Zero so use #
For i = 0 To iPos - 1
strFormat = strFormat & kPound
Next
End If
End If
'-------------------------
'If Float
' Append Decimal Formatting
'------------------------
If blnIsFloat Then
'Insert the Period
strFormat = strFormat & kPeriod
'Add Number Digits After Decimal
For i = 1 To NumDigitsAfterDecimal
strFormat = strFormat & kZero
Next
End If
'---------------------------------
'If Parantheses If Negative Number
'---------------------------------
If UseParensForNegativeNumbers Then
If CSng(Expression) < 0 Then
Expression = Right$(Expression, Len(Expression) - 1)
strFormat = "(" & strFormat & ")"
End If
End If
'--------------
'Insert Commas
'--------------
If GroupDigits Then
'This can Apply to Integer, Long, and Floats
'Put commas in Expression For 1000's, etc
'how many depends on Expression value
iLen = Len(Expression)
If blnIsFloat Then
For i = ((iPos - 1) - 3) To iLen Step 3
'get left section before insert
sLeft = Left$(strFormat, i)
'get right section after insert
sRight = Right$(strFormat, Len(strFormat) - i)
'Construct Format with commas
strFormat = sLeft & kComma & sRight
Next
Else
For i = 4 To iLen Step 3
'get left section before insert
sLeft = Left$(strFormat, i)
'get right section after insert
sRight = Right$(strFormat, Len(strFormat) - i)
'Construct Format with commas
strFormat = sLeft & kComma & sRight
Next
End If
End If 'GroupDigits
'Return the Formatted Number
FormatNumber = Format(Expression, strFormat)
End Function