<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="VB6Parse Library Reference - str - String">
<title>str - String - VB6Parse Library Reference</title>
<link rel="stylesheet" href="../../../assets/css/style.css">
<link rel="stylesheet" href="../../../assets/css/docs-style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<script src="../../../assets/js/theme-switcher.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/vbnet.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<body>
<header class="docs-header">
<div class="container">
<h1><a href="../../../index.html">VB6Parse</a> / <a href="../../../library/index.html">Library</a> / <a href="../../../library/functions/string/index.html">String</a> / str</h1>
<p class="tagline">VB6 Library Reference</p>
</div>
</header>
<nav class="docs-nav">
<div class="container">
<a href="../../../index.html">Home</a>
<a href="../../../library/index.html">Library Reference</a>
<a href="../../../documentation.html">Documentation</a>
<a href="https://docs.rs/vb6parse" target="_blank">API Docs</a>
<a href="https://github.com/scriptandcompile/vb6parse" target="_blank">GitHub</a>
<button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
<span class="theme-icon">🌙</span>
</button>
</div>
</nav>
<main class="container">
<article class="library-item">
<p>VB6 Str Function
The <code>Str</code> function converts a number to a string representation.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">Str(number)</code></pre>
<h2 id="parameters">Parameters</h2>
<ul>
<li><code>number</code>: Required. Any valid numeric expression (Long, Integer, Single, Double, Currency, Byte, Boolean, Variant).</li>
</ul>
<h2 id="returns">Returns</h2>
<p>Returns a <code>String</code> representing the numeric value. Positive numbers include a leading space for the sign position,
negative numbers include a leading minus sign.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>Str</code> function converts numeric values to their string representation:
- <strong>Always includes sign position</strong>: Positive numbers have a leading space, negative numbers have a leading minus sign (<code>-</code>)
- <strong>No thousands separators</strong>: Returns plain numeric string without commas or other formatting
- <strong>Scientific notation</strong>: Very large or very small numbers may use scientific notation (e.g., "1.23E+10")
- <strong>Decimal point</strong>: Uses period (<code>.</code>) as decimal separator, regardless of locale settings
- <strong>Boolean conversion</strong>: <code>True</code> becomes <code>"-1"</code>, <code>False</code> becomes <code>" 0"</code>
- <strong>Null handling</strong>: If <code>number</code> is <code>Null</code>, returns <code>Null</code> (not empty string)
- <strong>Variant support</strong>: Accepts Variant containing numeric values
- <strong>No currency symbol</strong>: Currency values converted without <code>$</code> or other symbols</p>
<h3 id="comparison-with-other-functions">Comparison with Other Functions</h3>
<ul>
<li><strong>Str vs <code>CStr</code></strong>: <code>Str</code> adds leading space for positive numbers, <code>CStr</code> does not</li>
<li><strong>Str vs Format$</strong>: <code>Str</code> has no formatting options, <code>Format$</code> provides extensive control</li>
<li><strong>Str vs Val</strong>: <code>Str</code> converts number to string, <code>Val</code> converts string to number (inverse operations)</li>
<li><strong>Str vs <code>LTrim</code>$</strong>: Often use <code>LTrim$(Str(number))</code> to remove leading space from positive numbers</li>
</ul>
<h2 id="typical-uses">Typical Uses</h2>
<ol>
<li><strong>Quick Number Display</strong>: Convert numbers to strings for display without formatting</li>
<li><strong>String Concatenation</strong>: Build messages or output by combining numbers with text</li>
<li><strong>File Output</strong>: Write numeric values to text files in plain format</li>
<li><strong>Debug Output</strong>: Display numeric values in debug messages with minimal formatting</li>
<li><strong>Data Export</strong>: Export numeric data to plain text format</li>
<li><strong>Sign Preservation</strong>: Maintain visual alignment when displaying columns of numbers</li>
<li><strong>Legacy Code</strong>: Support older code that relied on <code>Str</code> function behavior</li>
<li><strong>Simple Conversion</strong>: Convert numeric types to string without locale-specific formatting</li>
</ol>
<h2 id="basic-examples">Basic Examples</h2>
<h3 id="example-1-basic-number-conversion">Example 1: Basic Number Conversion</h3>
<pre><code class="language-vbnet">Dim result As String
result = Str(123) ' Returns " 123" (note leading space)
result = Str(-456) ' Returns "-456" (leading minus sign)
result = Str(0) ' Returns " 0" (leading space)
result = Str(3.14159) ' Returns " 3.14159"</code></pre>
<h3 id="example-2-removing-leading-space">Example 2: Removing Leading Space</h3>
<pre><code class="language-vbnet">Dim numStr As String
Dim value As Long
value = 100
' With leading space
numStr = Str(value) ' " 100"
' Without leading space
numStr = LTrim$(Str(value)) ' "100"
' Or use CStr instead
numStr = CStr(value) ' "100"</code></pre>
<h3 id="example-3-string-concatenation">Example 3: String Concatenation</h3>
<pre><code class="language-vbnet">Dim message As String
Dim count As Integer
Dim total As Double
count = 5
total = 123.45
message = "Count:" & Str(count) & ", Total:" & Str(total)
' Result: "Count: 5, Total: 123.45" (spaces from Str included)
message = "Count:" & LTrim$(Str(count)) & ", Total:" & LTrim$(Str(total))
' Result: "Count:5, Total:123.45" (no extra spaces)</code></pre>
<h3 id="example-4-boolean-conversion">Example 4: Boolean Conversion</h3>
<pre><code class="language-vbnet">Dim result As String
Dim flag As Boolean
flag = True
result = Str(flag) ' Returns "-1"
flag = False
result = Str(flag) ' Returns " 0"</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="pattern-1-build-display-string">Pattern 1: Build Display String</h3>
<pre><code class="language-vbnet">Function BuildSummary(items As Integer, amount As Currency) As String
' Build summary string with numbers
BuildSummary = "Items:" & LTrim$(Str(items)) & _
" Amount: $" & LTrim$(Str(amount))
End Function</code></pre>
<h3 id="pattern-2-write-to-file">Pattern 2: Write to File</h3>
<pre><code class="language-vbnet">Sub WriteDataToFile(filename As String, values() As Double)
Dim fileNum As Integer
Dim i As Integer
fileNum = FreeFile
Open filename For Output As #fileNum
For i = LBound(values) To UBound(values)
Print #fileNum, LTrim$(Str(values(i)))
Next i
Close #fileNum
End Sub</code></pre>
<h3 id="pattern-3-debug-output">Pattern 3: Debug Output</h3>
<pre><code class="language-vbnet">Sub DebugPrintValues(x As Double, y As Double, z As Double)
Debug.Print "X=" & LTrim$(Str(x)) & _
" Y=" & LTrim$(Str(y)) & _
" Z=" & LTrim$(Str(z))
End Sub</code></pre>
<h3 id="pattern-4-array-to-string">Pattern 4: Array to String</h3>
<pre><code class="language-vbnet">Function ArrayToString(arr() As Integer) As String
Dim i As Integer
Dim result As String
result = ""
For i = LBound(arr) To UBound(arr)
If i > LBound(arr) Then result = result & ","
result = result & LTrim$(Str(arr(i)))
Next i
ArrayToString = result
End Function</code></pre>
<h3 id="pattern-5-aligned-column-output">Pattern 5: Aligned Column Output</h3>
<pre><code class="language-vbnet">Sub PrintAlignedNumbers(values() As Long)
Dim i As Integer
Dim numStr As String
For i = LBound(values) To UBound(values)
numStr = Str(values(i)) ' Keep leading space/sign
Debug.Print Right$(Space(10) & numStr, 10) ' Right-align
Next i
End Sub</code></pre>
<h3 id="pattern-6-safe-null-handling">Pattern 6: Safe Null Handling</h3>
<pre><code class="language-vbnet">Function SafeStr(value As Variant) As String
' Handle potential Null values
If IsNull(value) Then
SafeStr = ""
ElseIf IsNumeric(value) Then
SafeStr = LTrim$(Str(value))
Else
SafeStr = CStr(value)
End If
End Function</code></pre>
<h3 id="pattern-7-build-csv-line">Pattern 7: Build CSV Line</h3>
<pre><code class="language-vbnet">Function BuildCSVLine(id As Long, quantity As Integer, price As Currency) As String
' Build comma-separated values
BuildCSVLine = LTrim$(Str(id)) & "," & _
LTrim$(Str(quantity)) & "," & _
LTrim$(Str(price))
End Function</code></pre>
<h3 id="pattern-8-number-to-padded-string">Pattern 8: Number to Padded String</h3>
<pre><code class="language-vbnet">Function NumberToPaddedString(value As Long, width As Integer) As String
Dim numStr As String
numStr = LTrim$(Str(value))
NumberToPaddedString = Right$(String$(width, "0") & numStr, width)
End Function</code></pre>
<h3 id="pattern-9-sign-aware-display">Pattern 9: Sign-Aware Display</h3>
<pre><code class="language-vbnet">Function DisplayWithSign(value As Double) As String
Dim numStr As String
numStr = Str(value) ' Keep sign/space
If Left$(numStr, 1) = " " Then
DisplayWithSign = "+" & LTrim$(numStr)
Else
DisplayWithSign = numStr ' Already has minus sign
End If
End Function</code></pre>
<h3 id="pattern-10-concatenate-multiple-values">Pattern 10: Concatenate Multiple Values</h3>
<pre><code class="language-vbnet">Function ConcatenateValues(ParamArray values() As Variant) As String
Dim i As Integer
Dim result As String
result = ""
For i = LBound(values) To UBound(values)
If i > LBound(values) Then result = result & " "
result = result & LTrim$(Str(values(i)))
Next i
ConcatenateValues = result
End Function</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="example-1-data-export-utility">Example 1: Data Export Utility</h3>
<pre><code class="language-vbnet">' Class: DataExporter
' Exports numeric data to various text formats
Option Explicit
Private m_Delimiter As String
Private m_IncludeHeader As Boolean
Private m_TrimSpaces As Boolean
Public Sub Initialize(delimiter As String, includeHeader As Boolean, trimSpaces As Boolean)
m_Delimiter = delimiter
m_IncludeHeader = includeHeader
m_TrimSpaces = trimSpaces
End Sub
Public Sub ExportToFile(filename As String, data() As Double, headers() As String)
Dim fileNum As Integer
Dim i As Integer
Dim j As Integer
Dim line As String
fileNum = FreeFile
Open filename For Output As #fileNum
' Write header if requested
If m_IncludeHeader Then
line = Join(headers, m_Delimiter)
Print #fileNum, line
End If
' Write data rows
For i = LBound(data, 1) To UBound(data, 1)
line = ""
For j = LBound(data, 2) To UBound(data, 2)
If j > LBound(data, 2) Then line = line & m_Delimiter
If m_TrimSpaces Then
line = line & LTrim$(Str(data(i, j)))
Else
line = line & Str(data(i, j))
End If
Next j
Print #fileNum, line
Next i
Close #fileNum
End Sub
Public Function ConvertRowToString(values() As Variant) As String
Dim i As Integer
Dim result As String
result = ""
For i = LBound(values) To UBound(values)
If i > LBound(values) Then result = result & m_Delimiter
If IsNumeric(values(i)) Then
If m_TrimSpaces Then
result = result & LTrim$(Str(values(i)))
Else
result = result & Str(values(i))
End If
Else
result = result & CStr(values(i))
End If
Next i
ConvertRowToString = result
End Function</code></pre>
<h3 id="example-2-number-formatter-module">Example 2: Number Formatter Module</h3>
<pre><code class="language-vbnet">' Module: NumberFormatter
' Utilities for converting numbers to formatted strings
Option Explicit
Public Function ToStringWithoutSpace(value As Variant) As String
' Convert number to string without leading space
If IsNull(value) Then
ToStringWithoutSpace = ""
ElseIf IsNumeric(value) Then
ToStringWithoutSpace = LTrim$(Str(value))
Else
ToStringWithoutSpace = CStr(value)
End If
End Function
Public Function ToFixedWidth(value As Double, width As Integer) As String
' Convert number to fixed-width string, right-aligned
Dim numStr As String
numStr = Str(value) ' Keep sign position
If Len(numStr) >= width Then
ToFixedWidth = numStr
Else
ToFixedWidth = Space(width - Len(numStr)) & numStr
End If
End Function
Public Function ToScientific(value As Double, decimals As Integer) As String
' Convert to scientific notation manually
Dim exponent As Integer
Dim mantissa As Double
Dim absValue As Double
If value = 0 Then
ToScientific = "0.0E+00"
Exit Function
End If
absValue = Abs(value)
exponent = Int(Log(absValue) / Log(10))
mantissa = value / (10 ^ exponent)
ToScientific = LTrim$(Str(Round(mantissa, decimals))) & "E" & _
IIf(exponent >= 0, "+", "") & LTrim$(Str(exponent))
End Function
Public Function PadInteger(value As Long, width As Integer) As String
' Pad integer with leading zeros
Dim numStr As String
numStr = LTrim$(Str(value))
If Len(numStr) >= width Then
PadInteger = numStr
Else
PadInteger = String$(width - Len(numStr), "0") & numStr
End If
End Function</code></pre>
<h3 id="example-3-report-builder-class">Example 3: Report Builder Class</h3>
<pre><code class="language-vbnet">' Class: ReportBuilder
' Builds formatted text reports with numeric data
Option Explicit
Private m_Lines As Collection
Private m_ColumnWidths() As Integer
Private m_ColumnCount As Integer
Public Sub Initialize(columnCount As Integer)
Set m_Lines = New Collection
m_ColumnCount = columnCount
ReDim m_ColumnWidths(1 To columnCount)
' Default column widths
Dim i As Integer
For i = 1 To columnCount
m_ColumnWidths(i) = 10
Next i
End Sub
Public Sub SetColumnWidth(column As Integer, width As Integer)
If column >= 1 And column <= m_ColumnCount Then
m_ColumnWidths(column) = width
End If
End Sub
Public Sub AddRow(ParamArray values() As Variant)
Dim i As Integer
Dim line As String
Dim cell As String
Dim colNum As Integer
line = ""
For i = LBound(values) To UBound(values)
colNum = i + 1
If colNum > m_ColumnCount Then Exit For
' Convert value to string
If IsNumeric(values(i)) Then
cell = Str(values(i)) ' Keep sign position for alignment
Else
cell = CStr(values(i))
End If
' Pad to column width
If Len(cell) < m_ColumnWidths(colNum) Then
cell = Space(m_ColumnWidths(colNum) - Len(cell)) & cell
End If
line = line & cell
Next i
m_Lines.Add line
End Sub
Public Function GetReport() As String
Dim i As Integer
Dim result As String
result = ""
For i = 1 To m_Lines.Count
result = result & m_Lines(i) & vbCrLf
Next i
GetReport = result
End Function
Public Sub Clear()
Set m_Lines = New Collection
End Sub</code></pre>
<h3 id="example-4-string-builder-for-numbers">Example 4: String Builder for Numbers</h3>
<pre><code class="language-vbnet">' Module: NumericStringBuilder
' Build strings from numeric arrays and collections
Option Explicit
Public Function JoinNumbers(numbers() As Double, delimiter As String, trimSpaces As Boolean) As String
Dim i As Integer
Dim result As String
Dim numStr As String
result = ""
For i = LBound(numbers) To UBound(numbers)
If i > LBound(numbers) Then result = result & delimiter
numStr = Str(numbers(i))
If trimSpaces Then numStr = LTrim$(numStr)
result = result & numStr
Next i
JoinNumbers = result
End Function
Public Function CreateTable(data() As Variant, rowCount As Integer, colCount As Integer) As String
Dim i As Integer
Dim j As Integer
Dim result As String
Dim row As String
result = ""
For i = 1 To rowCount
row = ""
For j = 1 To colCount
If j > 1 Then row = row & vbTab
If IsNumeric(data(i, j)) Then
row = row & LTrim$(Str(data(i, j)))
Else
row = row & CStr(data(i, j))
End If
Next j
result = result & row & vbCrLf
Next i
CreateTable = result
End Function
Public Function FormatNumberList(numbers As Collection, prefix As String, suffix As String) As String
Dim item As Variant
Dim result As String
Dim first As Boolean
first = True
result = ""
For Each item In numbers
If Not first Then result = result & ", "
result = result & prefix & LTrim$(Str(item)) & suffix
first = False
Next item
FormatNumberList = result
End Function
Public Function CreateSummaryLine(label As String, value As Double, width As Integer) As String
Dim numStr As String
Dim padding As Integer
numStr = LTrim$(Str(value))
padding = width - Len(label) - Len(numStr)
If padding > 0 Then
CreateSummaryLine = label & Space(padding) & numStr
Else
CreateSummaryLine = label & " " & numStr
End If
End Function</code></pre>
<h2 id="error-handling">Error Handling</h2>
<p>The <code>Str</code> function can raise the following errors:
- <strong>Error 13 (Type mismatch)</strong>: If <code>number</code> cannot be converted to a numeric value
- <strong>Error 94 (Invalid use of Null)</strong>: In some contexts when passing Null without proper handling</p>
<h2 id="performance-notes">Performance Notes</h2>
<ul>
<li>Very fast for basic numeric types (Integer, Long, Single, Double)</li>
<li>Slightly slower for Variant types due to type checking</li>
<li>No performance overhead from locale or formatting</li>
<li>Direct conversion without intermediate formatting steps</li>
<li>Consider <code>CStr</code> if leading space is always unwanted (avoids <code>LTrim$</code> call)</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<ol>
<li><strong>Use <code>LTrim$</code></strong> to remove leading space from positive numbers when space is unwanted</li>
<li><strong>Consider <code>CStr</code></strong> if you never need the leading space (cleaner code)</li>
<li><strong>Preserve sign position</strong> when aligning columns of numbers (keep the <code>Str</code> space)</li>
<li><strong>Handle Null values</strong> explicitly with <code>IsNull</code> check before calling <code>Str</code></li>
<li><strong>Use <code>Format$</code></strong> instead for formatted output (thousands separators, decimal places)</li>
<li><strong>Document behavior</strong> when <code>Str</code> is used in shared code (leading space can surprise developers)</li>
<li><strong>Combine with <code>Val</code></strong> for round-trip conversion (number → string → number)</li>
<li><strong>Avoid locale issues</strong> by using <code>Str</code> for culture-invariant numeric strings</li>
<li><strong>Cache results</strong> if converting the same number repeatedly in a loop</li>
<li><strong>Use type-specific functions</strong> like <code>CStr</code> when working with non-numeric types</li>
</ol>
<h2 id="comparison-table">Comparison Table</h2>
<table>
<thead>
<tr>
<th>Function</th>
<th>Input</th>
<th>Output</th>
<th>Leading Space</th>
<th>Formatting</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Str</code></td>
<td>Number</td>
<td>String</td>
<td>Yes (positive)</td>
<td>None</td>
</tr>
<tr>
<td><code>CStr</code></td>
<td>Any</td>
<td>String</td>
<td>No</td>
<td>None</td>
</tr>
<tr>
<td><code>Format$</code></td>
<td>Any</td>
<td>String</td>
<td>No</td>
<td>Extensive</td>
</tr>
<tr>
<td><code>Val</code></td>
<td>String</td>
<td>Double</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<td><code>LTrim$</code></td>
<td>String</td>
<td>String</td>
<td>Removes</td>
<td>None</td>
</tr>
</tbody>
</table>
<h2 id="platform-notes">Platform Notes</h2>
<ul>
<li>Available in VB6, VBA, and <code>VBScript</code></li>
<li>Behavior consistent across all platforms</li>
<li>Uses period (<code>.</code>) as decimal separator regardless of locale</li>
<li>Scientific notation format is standard across platforms</li>
<li>No localization or culture-specific formatting applied</li>
</ul>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Always includes leading space for positive numbers (often unwanted)</li>
<li>No formatting options (thousands separators, decimal places, etc.)</li>
<li>Cannot specify decimal precision</li>
<li>Cannot control scientific notation threshold</li>
<li>No currency symbol support</li>
<li>Null input can cause errors if not handled</li>
<li>No culture-aware formatting</li>
<li>Return value length is unpredictable (depends on number magnitude)</li>
</ul>
</article>
<div style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border-color);">
<p>
<a href="index.html">← Back to String</a> |
<a href="../index.html">View all functions</a>
</p>
</div>
</main>
<footer>
<div class="container">
<p>© 2024-2026 VB6Parse Contributors. Licensed under the MIT License.</p>
</div>
</footer>
</body>
</html>