<!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 - formatnumber - String">
<title>formatnumber - 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> / formatnumber</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">
<h1 id="formatnumber-function">FormatNumber Function</h1>
<p>Returns an expression formatted as a number.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">FormatNumber(expression[, numdigitsafterdecimal[, includeleadingdigit[, useparensfornegativenumbers[, groupdigits]]]])</code></pre>
<h2 id="parameters">Parameters</h2>
<ul>
<li><strong>expression</strong>: Required. Expression to be formatted.</li>
<li><strong>numdigitsafterdecimal</strong>: Optional. <code>Numeric</code> value indicating how many places to the right of the decimal are displayed. Default is -1, which indicates the computer's regional settings are used.</li>
<li><strong>includeleadingdigit</strong>: Optional. Tristate constant that indicates whether a leading zero is displayed for fractional values. See Settings for values.</li>
<li><strong>useparensfornegativenumbers</strong>: Optional. Tristate constant that indicates whether to place negative values within parentheses. See Settings for values.</li>
<li><strong>groupdigits</strong>: Optional. Tristate constant that indicates whether numbers are grouped using the group delimiter specified in the computer's regional settings. See Settings for values.</li>
</ul>
<h2 id="settings">Settings</h2>
<p>The includeleadingdigit, useparensfornegativenumbers, and groupdigits arguments have the following settings:
- <strong>vbTrue</strong> (-1): True
- <strong>vbFalse</strong> (0): False
- <strong>vbUseDefault</strong> (-2): Use the setting from the computer's regional settings</p>
<h2 id="return-value">Return Value</h2>
<p>Returns a Variant of subtype String containing the expression formatted as a number.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>FormatNumber</code> function provides a simple way to format numeric values using
the system's locale settings. Unlike <code>FormatCurrency</code>, it does not add a currency symbol,
making it ideal for general numeric display.
<strong>Important Characteristics:</strong>
- Uses system locale for formatting
- Default: 2 decimal places (from regional settings)
- Automatically adds thousand separators (if groupdigits=True)
- Negative numbers can be displayed with parentheses or minus sign
- Leading zeros controlled by regional settings or parameter
- No currency symbol added
- Returns empty string if expression is Null
- More convenient than Format for simple number formatting
- Less flexible than Format for custom patterns
- Locale-aware (respects user's regional settings)</p>
<h2 id="typical-uses">Typical Uses</h2>
<ul>
<li>Display numeric values in reports</li>
<li>Format percentages (without % symbol)</li>
<li>Show quantities and measurements</li>
<li>Display statistical values</li>
<li>Format calculated results</li>
<li>Show decimal precision in user interfaces</li>
<li>Display population or large numbers</li>
<li>Format scientific data</li>
</ul>
<h2 id="examples">Examples</h2>
<h3 id="basic-usage">Basic Usage</h3>
<pre><code class="language-vbnet">Dim value As Double
value = 1234.567
' Default formatting (2 decimal places, system settings)
Debug.Print FormatNumber(value) ' 1,234.57
' No decimal places
Debug.Print FormatNumber(value, 0) ' 1,235
' Three decimal places
Debug.Print FormatNumber(value, 3) ' 1,234.567
' Four decimal places
Debug.Print FormatNumber(value, 4) ' 1,234.5670</code></pre>
<h3 id="handling-negative-values">Handling Negative Values</h3>
<pre><code class="language-vbnet">Dim negative As Double
negative = -1250.50
' Default negative (with minus sign)
Debug.Print FormatNumber(negative) ' -1,250.50
' Parentheses for negative
Debug.Print FormatNumber(negative, 2, , vbTrue) ' (1,250.50)
' No parentheses (explicit)
Debug.Print FormatNumber(negative, 2, , vbFalse) ' -1,250.50</code></pre>
<h3 id="control-leading-digits">Control Leading Digits</h3>
<pre><code class="language-vbnet">Dim fraction As Double
fraction = 0.75
' With leading zero (default)
Debug.Print FormatNumber(fraction) ' 0.75
' No leading zero
Debug.Print FormatNumber(fraction, 2, vbFalse) ' .75
' Explicit leading zero
Debug.Print FormatNumber(fraction, 2, vbTrue) ' 0.75</code></pre>
<h3 id="control-grouping">Control Grouping</h3>
<pre><code class="language-vbnet">Dim largeNumber As Double
largeNumber = 1234567.89
' With grouping (thousands separators)
Debug.Print FormatNumber(largeNumber, 2, , , vbTrue) ' 1,234,567.89
' Without grouping
Debug.Print FormatNumber(largeNumber, 2, , , vbFalse) ' 1234567.89</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="display-statistical-results">Display Statistical Results</h3>
<pre><code class="language-vbnet">Sub DisplayStatistics(data() As Double)
Dim total As Double
Dim average As Double
Dim i As Long
total = 0
For i = LBound(data) To UBound(data)
total = total + data(i)
Next i
average = total / (UBound(data) - LBound(data) + 1)
Debug.Print "Count: " & FormatNumber(UBound(data) + 1, 0)
Debug.Print "Total: " & FormatNumber(total, 2)
Debug.Print "Average: " & FormatNumber(average, 2)
End Sub</code></pre>
<h3 id="format-population-numbers">Format Population Numbers</h3>
<pre><code class="language-vbnet">Function FormatPopulation(population As Long) As String
FormatPopulation = FormatNumber(population, 0, , , vbTrue)
End Function
' Usage
Debug.Print "Population: " & FormatPopulation(8500000) ' Population: 8,500,000</code></pre>
<h3 id="display-measurement-with-precision">Display Measurement with Precision</h3>
<pre><code class="language-vbnet">Function FormatMeasurement(value As Double, decimals As Integer, _
unit As String) As String
FormatMeasurement = FormatNumber(value, decimals) & " " & unit
End Function
' Usage
Debug.Print FormatMeasurement(12.5678, 2, "cm") ' 12.57 cm
Debug.Print FormatMeasurement(98.6, 1, "°F") ' 98.6 °F</code></pre>
<h3 id="format-gridreport-data">Format Grid/Report Data</h3>
<pre><code class="language-vbnet">Sub PopulateDataGrid(grid As MSFlexGrid, values() As Double)
Dim i As Long
grid.Rows = UBound(values) + 2
grid.TextMatrix(0, 0) = "Index"
grid.TextMatrix(0, 1) = "Value"
For i = LBound(values) To UBound(values)
grid.TextMatrix(i + 1, 0) = FormatNumber(i, 0)
grid.TextMatrix(i + 1, 1) = FormatNumber(values(i), 2)
Next i
End Sub</code></pre>
<h3 id="display-percentage-without-symbol">Display Percentage (without symbol)</h3>
<pre><code class="language-vbnet">Function FormatPercentValue(value As Double, decimals As Integer) As String
' Convert to percentage value (multiply by 100)
FormatPercentValue = FormatNumber(value * 100, decimals)
End Function
' Usage
Debug.Print FormatPercentValue(0.1234, 2) ' 12.34
Debug.Print FormatPercentValue(0.5, 0) ' 50</code></pre>
<h3 id="format-scorerating-display">Format Score/Rating Display</h3>
<pre><code class="language-vbnet">Function FormatScore(score As Double, maxScore As Double) As String
Dim percentage As Double
percentage = (score / maxScore) * 100
FormatScore = FormatNumber(score, 1) & " / " & _
FormatNumber(maxScore, 0) & " (" & _
FormatNumber(percentage, 1) & "%)"
End Function
' Usage
Debug.Print FormatScore(87.5, 100) ' 87.5 / 100 (87.5%)</code></pre>
<h3 id="display-large-numbers-with-suffixes">Display Large Numbers with Suffixes</h3>
<pre><code class="language-vbnet">Function FormatLargeNumber(value As Double) As String
Const Million = 1000000
Const Billion = 1000000000
If Abs(value) >= Billion Then
FormatLargeNumber = FormatNumber(value / Billion, 2) & "B"
ElseIf Abs(value) >= Million Then
FormatLargeNumber = FormatNumber(value / Million, 2) & "M"
ElseIf Abs(value) >= 1000 Then
FormatLargeNumber = FormatNumber(value / 1000, 2) & "K"
Else
FormatLargeNumber = FormatNumber(value, 2)
End If
End Function
' Usage
Debug.Print FormatLargeNumber(1500000) ' 1.50M
Debug.Print FormatLargeNumber(2500000000) ' 2.50B</code></pre>
<h3 id="format-comparison-display">Format Comparison Display</h3>
<pre><code class="language-vbnet">Function FormatComparison(actual As Double, expected As Double) As String
Dim difference As Double
Dim percentDiff As Double
difference = actual - expected
If expected <> 0 Then
percentDiff = (difference / expected) * 100
End If
FormatComparison = "Actual: " & FormatNumber(actual, 2) & vbCrLf & _
"Expected: " & FormatNumber(expected, 2) & vbCrLf & _
"Difference: " & FormatNumber(difference, 2, , vbTrue) & vbCrLf & _
"% Difference: " & FormatNumber(percentDiff, 2, , vbTrue)
End Function</code></pre>
<h3 id="listbox-population-with-numbers"><code>ListBox</code> Population with Numbers</h3>
<pre><code class="language-vbnet">Sub PopulateNumberList(lst As ListBox, values() As Double, decimals As Integer)
Dim i As Long
lst.Clear
For i = LBound(values) To UBound(values)
lst.AddItem FormatNumber(values(i), decimals)
Next i
End Sub</code></pre>
<h3 id="format-database-numeric-display">Format Database Numeric Display</h3>
<pre><code class="language-vbnet">Function GetFormattedNumber(rs As ADODB.Recordset, fieldName As String, _
Optional decimals As Integer = 2) As String
If IsNull(rs.Fields(fieldName).Value) Then
GetFormattedNumber = "N/A"
Else
GetFormattedNumber = FormatNumber(rs.Fields(fieldName).Value, decimals)
End If
End Function</code></pre>
<h3 id="display-summary-totals">Display Summary Totals</h3>
<pre><code class="language-vbnet">Sub DisplaySummary(items As Collection)
Dim item As Variant
Dim count As Long
Dim total As Double
Dim average As Double
Dim maxVal As Double
Dim minVal As Double
count = items.Count
total = 0
maxVal = -1E+308 ' Smallest possible Double
minVal = 1E+308 ' Largest possible Double
For Each item In items
total = total + item.Value
If item.Value > maxVal Then maxVal = item.Value
If item.Value < minVal Then minVal = item.Value
Next item
average = total / count
Debug.Print "Summary Statistics"
Debug.Print String(50, "=")
Debug.Print "Count: ", FormatNumber(count, 0)
Debug.Print "Total: ", FormatNumber(total, 2)
Debug.Print "Average: ", FormatNumber(average, 2)
Debug.Print "Maximum: ", FormatNumber(maxVal, 2)
Debug.Print "Minimum: ", FormatNumber(minVal, 2)
End Sub</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="flexible-number-formatter">Flexible Number Formatter</h3>
<pre><code class="language-vbnet">Function FormatNumberEx(value As Double, _
Optional decimals As Integer = 2, _
Optional useParens As Boolean = False, _
Optional useGroups As Boolean = True) As String
Dim leadingDigit As VbTriState
Dim parens As VbTriState
Dim groups As VbTriState
leadingDigit = vbTrue
parens = IIf(useParens, vbTrue, vbFalse)
groups = IIf(useGroups, vbTrue, vbFalse)
FormatNumberEx = FormatNumber(value, decimals, leadingDigit, parens, groups)
End Function</code></pre>
<h3 id="accounting-style-formatter">Accounting-Style Formatter</h3>
<pre><code class="language-vbnet">Function FormatAccounting(value As Double, Optional decimals As Integer = 2) As String
' Always show parentheses for negatives, use grouping
FormatAccounting = FormatNumber(value, decimals, vbTrue, vbTrue, vbTrue)
End Function
' Usage
Debug.Print FormatAccounting(1234.56) ' 1,234.56
Debug.Print FormatAccounting(-789.12) ' (789.12)</code></pre>
<h3 id="dynamic-precision-formatter">Dynamic Precision Formatter</h3>
<pre><code class="language-vbnet">Function FormatNumberDynamic(value As Double) As String
' Adjust precision based on magnitude
If Abs(value) >= 1000 Then
' Large numbers: no decimals
FormatNumberDynamic = FormatNumber(value, 0)
ElseIf Abs(value) >= 1 Then
' Regular: 2 decimals
FormatNumberDynamic = FormatNumber(value, 2)
ElseIf Abs(value) >= 0.01 Then
' Small: 4 decimals
FormatNumberDynamic = FormatNumber(value, 4)
Else
' Very small: 6 decimals
FormatNumberDynamic = FormatNumber(value, 6)
End If
End Function</code></pre>
<h3 id="tablereport-alignment">Table/Report Alignment</h3>
<pre><code class="language-vbnet">Function FormatNumberAligned(value As Double, width As Integer, _
Optional decimals As Integer = 2) As String
Dim formatted As String
formatted = FormatNumber(value, decimals, vbTrue, vbTrue, vbTrue)
' Right-align in field
If Len(formatted) < width Then
FormatNumberAligned = Space(width - Len(formatted)) & formatted
Else
FormatNumberAligned = formatted
End If
End Function</code></pre>
<h3 id="scientific-data-formatter">Scientific Data Formatter</h3>
<pre><code class="language-vbnet">Function FormatScientificValue(value As Double, _
significantDigits As Integer) As String
If Abs(value) >= 1000 Or Abs(value) < 0.01 Then
' Use scientific notation for very large/small
FormatScientificValue = Format(value, "0." & String(significantDigits - 1, "0") & "E+00")
Else
' Use regular formatting
FormatScientificValue = FormatNumber(value, significantDigits)
End If
End Function</code></pre>
<h3 id="conditional-formatting">Conditional Formatting</h3>
<pre><code class="language-vbnet">Function FormatNumberConditional(value As Double) As String
If value > 0 Then
FormatNumberConditional = "+" & FormatNumber(value, 2)
ElseIf value < 0 Then
FormatNumberConditional = FormatNumber(value, 2, , vbTrue)
Else
FormatNumberConditional = FormatNumber(0, 2)
End If
End Function</code></pre>
<h2 id="error-handling">Error Handling</h2>
<pre><code class="language-vbnet">Function SafeFormatNumber(value As Variant, _
Optional decimals As Integer = 2) As String
On Error GoTo ErrorHandler
If IsNull(value) Then
SafeFormatNumber = "N/A"
ElseIf Not IsNumeric(value) Then
SafeFormatNumber = "Invalid"
Else
SafeFormatNumber = FormatNumber(CDbl(value), decimals)
End If
Exit Function
ErrorHandler:
Select Case Err.Number
Case 13 ' Type mismatch
SafeFormatNumber = "Type Error"
Case 6 ' Overflow
SafeFormatNumber = "Overflow"
Case 5 ' Invalid procedure call
SafeFormatNumber = "Invalid"
Case Else
SafeFormatNumber = "Error"
End Select
End Function</code></pre>
<h3 id="common-errors">Common Errors</h3>
<ul>
<li><strong>Error 13</strong> (Type Mismatch): Expression cannot be converted to numeric</li>
<li><strong>Error 6</strong> (Overflow): Value too large for Double</li>
<li><strong>Error 5</strong> (Invalid procedure call): Invalid decimal places parameter</li>
</ul>
<h2 id="performance-considerations">Performance Considerations</h2>
<ul>
<li><code>FormatNumber</code> is fast for simple formatting</li>
<li>Slightly slower than <code>Format</code> for custom patterns</li>
<li>Faster than building format strings manually</li>
<li>Locale lookups cached by system</li>
<li>Avoid repeated calls in tight loops if possible</li>
<li>Consider caching formatted values for display</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<h3 id="use-formatnumber-for-general-numeric-display">Use <code>FormatNumber</code> for General Numeric Display</h3>
<pre><code class="language-vbnet">' Good - Locale-aware, user-friendly
lblValue.Caption = FormatNumber(total, 2)
' Less portable - Hard-coded format
lblValue.Caption = Format(total, "0.00")</code></pre>
<h3 id="handle-null-values">Handle Null Values</h3>
<pre><code class="language-vbnet">' Good - Check for Null
If Not IsNull(value) Then
formatted = FormatNumber(value, 2)
Else
formatted = "N/A"
End If</code></pre>
<h3 id="be-consistent-with-decimal-places">Be Consistent with Decimal Places</h3>
<pre><code class="language-vbnet">' Good - Use constants for consistency
Const DECIMAL_PLACES = 2
result1 = FormatNumber(value1, DECIMAL_PLACES)
result2 = FormatNumber(value2, DECIMAL_PLACES)</code></pre>
<h2 id="comparison-with-other-functions">Comparison with Other Functions</h2>
<h3 id="formatnumber-vs-formatcurrency"><code>FormatNumber</code> vs <code>FormatCurrency</code></h3>
<pre><code class="language-vbnet">' FormatNumber - No currency symbol
result = FormatNumber(1234.56) ' 1,234.56
' FormatCurrency - Adds currency symbol
result = FormatCurrency(1234.56) ' $1,234.56</code></pre>
<h3 id="formatnumber-vs-format"><code>FormatNumber</code> vs <code>Format</code></h3>
<pre><code class="language-vbnet">' FormatNumber - Simple, predefined
result = FormatNumber(1234.56, 2)
' Format - More control, custom patterns
result = Format(1234.56, "#,##0.00")</code></pre>
<h3 id="formatnumber-vs-formatpercent"><code>FormatNumber</code> vs <code>FormatPercent</code></h3>
<pre><code class="language-vbnet">' FormatNumber - No percent symbol, no multiplication
result = FormatNumber(0.1234 * 100, 2) ' 12.34
' FormatPercent - Multiplies by 100, adds %
result = FormatPercent(0.1234) ' 12.34%</code></pre>
<h3 id="formatnumber-vs-strcstr"><code>FormatNumber</code> vs <code>Str</code>/<code>CStr</code></h3>
<pre><code class="language-vbnet">' FormatNumber - Full formatting
result = FormatNumber(1234.56) ' 1,234.56
' Str - Basic conversion, no formatting
result = Str(1234.56) ' " 1234.56"
' CStr - Basic conversion
result = CStr(1234.56) ' "1234.56"</code></pre>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Uses system locale (cannot specify different locale)</li>
<li>All parameters optional, making errors less obvious</li>
<li>Tristate parameters can be confusing</li>
<li>No built-in rounding mode control</li>
<li>Cannot format with custom patterns</li>
<li>No control over decimal/thousand separators</li>
<li>Limited to numeric types</li>
</ul>
<h2 id="regional-settings-impact">Regional Settings Impact</h2>
<p>The <code>FormatNumber</code> function behavior varies by locale:
- <strong>United States</strong>: 1,234.56
- <strong>European Union</strong>: 1.234,56 (note decimal/thousand separators swapped)
- <strong>Switzerland</strong>: 1'234.56 (apostrophe as separator)
- <strong>India</strong>: 12,34,567.89 (different grouping pattern)</p>
<h2 id="related-functions">Related Functions</h2>
<ul>
<li><code>Format</code>: More flexible formatting with custom patterns</li>
<li><code>FormatCurrency</code>: Format numbers as currency</li>
<li><code>FormatPercent</code>: Format numbers as percentages</li>
<li><code>FormatDateTime</code>: Format date/time values</li>
<li><code>Round</code>: Round numbers to specified decimal places</li>
<li><code>Int</code>: Return integer portion of a number</li>
<li><code>CDbl</code>: Convert expression to Double</li>
<li><code>IsNumeric</code>: Check if expression can be converted to numeric</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>