Visual Basic 6:
'Inserts 'Insert' Every Interval Characters in InputStr and returns the result.
Public Function EveryN(ByVal InputStr As String, ByVal Interval As Integer, ByVal Insert As String) As String
'there are a few ways to do this, the most common is to iterate character by character, but that is rather slow, particularly
'since String concat is typically done a tad slowly on VB.
'instead, we'll split the string into an array where each element holds Interval characters from the original string. Then
'we can use the built in Join function to connect them together.
Dim Strparts() As String
Dim NumElements As Integer
NumElements = (Len(InputStr) \ Interval) + Abs((Len(InputStr) Mod Interval > 0))
ReDim Strparts(NumElements - 1)
Dim I As Long
Dim StartPos As Long
For I = 0 To NumElements - 1
StartPos = (I * Interval) + 1
Strparts(I) = Mid$(InputStr, StartPos, Interval)
Next I
EveryN = Join(Strparts, Insert)
End Function
Sample Usage:
Dim Strtest As String
Dim I As Long, J As Long
For I = 0 To 10
For J = 0 To 9
Strtest = Strtest + Trim$(Str$(J))
Next J, I
Dim result As String
result = EveryN(Strtest, 5, ",")
MsgBox (result)
Visual Basic .NET:
Public Function EveryN(ByVal InputStr As String, ByVal Interval As Integer, ByVal Insert As String) As String
Dim NumElements As Integer
NumElements = (Len(InputStr) \ Interval) + IIf((Len(InputStr) Mod Interval > 0), 1, 0)
Dim strbuild As New System.Text.StringBuilder
Dim I As Long, useLength As Integer = Interval
Dim StartPos As Long
For I = 0 To NumElements - 1
StartPos = (I * Interval)
If (InputStr.Length - StartPos < Interval) Then
strbuild.Append(InputStr.Substring(StartPos))
Else
strbuild.Append(InputStr.Substring(StartPos, Interval))
End If
If I < NumElements - 1 Then strbuild.Append(",")
Next I
Return strbuild.ToString()
End Function
Sample usage:
Sub Main()
Dim Strtest As String = String.Empty
Dim I As Long, J As Long
For I = 0 To 10
For J = 0 To 9
Strtest += Trim$(Str$(J))
Next J, I
Dim result As String
result = EveryN(Strtest, 5, ",")
Console.WriteLine(result)
Console.ReadKey()
End Sub
Also, if you just want standard, decimal after 3 characters, you can use Format(number,"#,###")