<!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 - formatpercent - String">
<title>formatpercent - 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> / formatpercent</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>FormatPercent Function
Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.</p>
<h1 id="syntax">Syntax</h1>
<pre><code class="language-vbnet">FormatPercent(expression[, numdigitsafterdecimal[, includeleadingdigit[, useparensfornegativenumbers[, groupdigits]]]])</code></pre>
<h1 id="parameters">Parameters</h1>
<ul>
<li><code>expression</code> - Required. Expression to be formatted as a percentage.</li>
<li><code>numdigitsafterdecimal</code> - Optional. Numeric value indicating how many places to the right of the decimal are displayed.
Default value is -1, which indicates that the computer's regional settings are used.</li>
<li><code>includeleadingdigit</code> - Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values.
See Settings section for values.</li>
<li><code>useparensfornegativenumbers</code> - Optional. Tristate constant that indicates whether or not to place negative values within parentheses.
See Settings section for values.</li>
<li><code>groupdigits</code> - Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter
specified in the computer's regional settings. See Settings section for values.</li>
</ul>
<h1 id="settings">Settings</h1>
<p>The <code>includeleadingdigit</code>, <code>useparensfornegativenumbers</code>, and <code>groupdigits</code> arguments have the following settings:</p>
<table>
<thead>
<tr>
<th>Constant</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>vbTrue</td>
<td>-1</td>
<td>True</td>
</tr>
<tr>
<td>vbFalse</td>
<td>0</td>
<td>False</td>
</tr>
<tr>
<td>vbUseDefault</td>
<td>-2</td>
<td>Use the setting from the computer's regional settings</td>
</tr>
</tbody>
</table>
<h1 id="return-value">Return Value</h1>
<p>Returns a Variant of subtype String containing the expression formatted as a percentage with a trailing % character.</p>
<h1 id="remarks">Remarks</h1>
<ul>
<li>The <code>FormatPercent</code> function multiplies the numeric value by 100 and appends a percent sign.</li>
<li>When one or more optional arguments are omitted, the computer's regional settings provide the default values.</li>
<li>The number is formatted according to the computer's locale settings.</li>
<li>If the expression is <code>Null</code>, <code>FormatPercent</code> returns an empty string.</li>
<li>The default number of decimal places is 2 (from regional settings).</li>
</ul>
<h1 id="typical-uses">Typical Uses</h1>
<ul>
<li>Displaying statistical percentages (success rates, completion rates)</li>
<li>Financial ratios (profit margins, growth rates, interest rates)</li>
<li>Survey results and poll data</li>
<li>Progress indicators and completion percentages</li>
<li>Conversion rates and efficiency metrics</li>
<li>Grade percentages and test scores</li>
</ul>
<h1 id="basic-usage-examples">Basic Usage Examples</h1>
<pre><code class="language-vbnet">' Default formatting (2 decimal places from regional settings)
result = FormatPercent(0.75) ' Returns: "75.00%"
result = FormatPercent(0.5) ' Returns: "50.00%"
result = FormatPercent(1.25) ' Returns: "125.00%"
' Handling negative percentages
result = FormatPercent(-0.15) ' Returns: "-15.00%"
result = FormatPercent(-0.05, 2, , vbTrue) ' Returns: "(5.00)%"
' Controlling decimal places
result = FormatPercent(0.3333, 0) ' Returns: "33%"
result = FormatPercent(0.3333, 2) ' Returns: "33.33%"
result = FormatPercent(0.3333, 4) ' Returns: "33.3300%"
' Leading digit control
result = FormatPercent(0.005, 2, vbTrue) ' Returns: "0.50%"
result = FormatPercent(0.005, 2, vbFalse) ' Returns: ".50%"</code></pre>
<h1 id="common-patterns">Common Patterns</h1>
<h2 id="1-success-rate-display">1. Success Rate Display</h2>
<pre><code class="language-vbnet">Dim successful As Long
Dim total As Long
Dim rate As Double
successful = 85
total = 100
rate = successful / total
MsgBox "Success Rate: " & FormatPercent(rate, 1) ' "Success Rate: 85.0%"</code></pre>
<h2 id="2-financial-ratios">2. Financial Ratios</h2>
<pre><code class="language-vbnet">Dim profit As Currency
Dim revenue As Currency
Dim margin As Double
profit = 25000
revenue = 100000
margin = profit / revenue
lblMargin.Caption = "Profit Margin: " & FormatPercent(margin, 2) ' "Profit Margin: 25.00%"</code></pre>
<h2 id="3-survey-results">3. Survey Results</h2>
<pre><code class="language-vbnet">Dim yesVotes As Long
Dim totalVotes As Long
yesVotes = 347
totalVotes = 500
txtResult.Text = FormatPercent(yesVotes / totalVotes, 1) ' "69.4%"</code></pre>
<h2 id="4-progress-indicator">4. Progress Indicator</h2>
<pre><code class="language-vbnet">Dim completed As Long
Dim total As Long
Dim progress As Double
completed = 45
total = 100
progress = completed / total
lblProgress.Caption = "Progress: " & FormatPercent(progress, 0) ' "Progress: 45%"</code></pre>
<h2 id="5-growth-rate-calculation">5. Growth Rate Calculation</h2>
<pre><code class="language-vbnet">Dim currentValue As Double
Dim previousValue As Double
Dim growth As Double
currentValue = 125000
previousValue = 100000
growth = (currentValue - previousValue) / previousValue
MsgBox "Growth: " & FormatPercent(growth, 1) ' "Growth: 25.0%"</code></pre>
<h2 id="6-grade-percentage">6. Grade Percentage</h2>
<pre><code class="language-vbnet">Dim score As Long
Dim maxScore As Long
Dim percentage As Double
score = 87
maxScore = 100
percentage = score / maxScore
lblGrade.Caption = "Score: " & FormatPercent(percentage, 0) ' "Score: 87%"</code></pre>
<h2 id="7-comparison-display">7. Comparison Display</h2>
<pre><code class="language-vbnet">Dim actual As Double
Dim target As Double
Dim achievement As Double
actual = 95000
target = 100000
achievement = actual / target
lblStatus.Caption = "Target Achievement: " & FormatPercent(achievement, 1) ' "Target Achievement: 95.0%"</code></pre>
<h2 id="8-listbox-population-with-percentages">8. <code>ListBox</code> Population with Percentages</h2>
<pre><code class="language-vbnet">Dim i As Integer
Dim values() As Double
Dim total As Double
values = Array(15.5, 28.3, 42.1, 14.1)
total = 100
For i = 0 To UBound(values)
lstResults.AddItem FormatPercent(values(i) / total, 1)
Next i</code></pre>
<h2 id="9-database-field-display">9. Database Field Display</h2>
<pre><code class="language-vbnet">Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT CompletionRate FROM Projects", conn
While Not rs.EOF
Debug.Print FormatPercent(rs("CompletionRate"), 0)
rs.MoveNext
Wend</code></pre>
<h2 id="10-multiple-percentages-in-report">10. Multiple Percentages in Report</h2>
<pre><code class="language-vbnet">Dim passed As Long, failed As Long, total As Long
Dim report As String
passed = 85
failed = 15
total = passed + failed
report = "Passed: " & FormatPercent(passed / total, 1) & vbCrLf & _
"Failed: " & FormatPercent(failed / total, 1)
' "Passed: 85.0%
' Failed: 15.0%"</code></pre>
<h1 id="advanced-usage">Advanced Usage</h1>
<h2 id="1-flexible-percentage-formatter">1. Flexible Percentage Formatter</h2>
<pre><code class="language-vbnet">Function DisplayPercentage(value As Double, Optional precision As Integer = 1) As String
If value < 0.01 Then
DisplayPercentage = FormatPercent(value, 3) ' More precision for small values
ElseIf value > 1 Then
DisplayPercentage = FormatPercent(value, 0) ' No decimals for large percentages
Else
DisplayPercentage = FormatPercent(value, precision)
End If
End Function</code></pre>
<h2 id="2-comparison-with-color-coding">2. Comparison with Color Coding</h2>
<pre><code class="language-vbnet">Function FormatVariance(actual As Double, target As Double) As String
Dim variance As Double
variance = (actual - target) / target
FormatVariance = FormatPercent(variance, 1)
If variance > 0 Then
lblVariance.ForeColor = vbGreen ' Positive variance
ElseIf variance < 0 Then
lblVariance.ForeColor = vbRed ' Negative variance
End If
End Function</code></pre>
<h2 id="3-dynamic-precision-based-on-value">3. Dynamic Precision Based on Value</h2>
<pre><code class="language-vbnet">Function SmartFormatPercent(value As Double) As String
Dim absValue As Double
absValue = Abs(value)
Select Case absValue
Case Is < 0.0001
SmartFormatPercent = FormatPercent(value, 4)
Case Is < 0.01
SmartFormatPercent = FormatPercent(value, 3)
Case Is < 1
SmartFormatPercent = FormatPercent(value, 2)
Case Else
SmartFormatPercent = FormatPercent(value, 1)
End Select
End Function</code></pre>
<h2 id="4-table-alignment-with-percentages">4. Table Alignment with Percentages</h2>
<pre><code class="language-vbnet">Function AlignedPercentage(value As Double, width As Integer) As String
Dim formatted As String
formatted = FormatPercent(value, 2)
AlignedPercentage = Space(width - Len(formatted)) & formatted
End Function
' Usage in grid or report
For i = 1 To 10
Debug.Print AlignedPercentage(data(i), 12)
Next i</code></pre>
<h2 id="5-statistical-analysis-display">5. Statistical Analysis Display</h2>
<pre><code class="language-vbnet">Type StatisticsResult
Mean As Double
StdDev As Double
Confidence As Double
End Type
Function FormatStatistics(stats As StatisticsResult) As String
FormatStatistics = "Mean: " & FormatPercent(stats.Mean, 2) & vbCrLf & _
"Std Dev: " & FormatPercent(stats.StdDev, 2) & vbCrLf & _
"Confidence: " & FormatPercent(stats.Confidence, 1)
End Function</code></pre>
<h2 id="6-conditional-formatting-for-thresholds">6. Conditional Formatting for Thresholds</h2>
<pre><code class="language-vbnet">Sub DisplayMetricWithThreshold(metric As Double, threshold As Double, lbl As Label)
lbl.Caption = FormatPercent(metric, 1)
If metric >= threshold Then
lbl.BackColor = vbGreen
lbl.ForeColor = vbWhite
ElseIf metric >= threshold * 0.8 Then
lbl.BackColor = vbYellow
lbl.ForeColor = vbBlack
Else
lbl.BackColor = vbRed
lbl.ForeColor = vbWhite
End If
End Sub</code></pre>
<h1 id="error-handling">Error Handling</h1>
<pre><code class="language-vbnet">Function SafeFormatPercent(value As Variant) As String
On Error GoTo ErrorHandler
If IsNull(value) Then
SafeFormatPercent = "N/A"
Exit Function
End If
If Not IsNumeric(value) Then
SafeFormatPercent = "Invalid"
Exit Function
End If
SafeFormatPercent = FormatPercent(CDbl(value), 2)
Exit Function
ErrorHandler:
SafeFormatPercent = "Error"
End Function</code></pre>
<p>Common errors:
- <strong>Error 13 (Type mismatch)</strong>: Occurs when expression cannot be converted to a numeric value.
- <strong>Error 6 (Overflow)</strong>: Can occur with extremely large or small values.
- <strong>Error 5 (Invalid procedure call)</strong>: May occur with invalid argument values.</p>
<h1 id="performance-considerations">Performance Considerations</h1>
<ul>
<li><code>FormatPercent</code> is relatively fast for single values but can be optimized in loops</li>
<li>For large datasets, consider caching formatted values</li>
<li>The multiplication by 100 is automatic and efficient</li>
<li>Regional settings lookup may have slight overhead</li>
</ul>
<h1 id="best-practices">Best Practices</h1>
<ol>
<li>Use appropriate decimal places for your context (financial: 2, statistics: 1, progress: 0)</li>
<li>Consider the audience when choosing precision</li>
<li>Handle division by zero before calling <code>FormatPercent</code></li>
<li>Use consistent formatting throughout your application</li>
<li>Remember that the input is a decimal (0.5 = 50%)</li>
<li>Consider using parentheses for negative values in financial contexts</li>
</ol>
<h1 id="comparison-with-other-functions">Comparison with Other Functions</h1>
<ul>
<li><strong><code>FormatNumber</code></strong>: Does not multiply by 100 or add %, gives more control over formatting</li>
<li><strong><code>FormatCurrency</code></strong>: Adds currency symbol instead of %, doesn't multiply by 100</li>
<li><strong>Format with "%"</strong>: More flexible but requires manual multiplication by 100</li>
<li><strong><code>Str</code>/<code>CStr</code></strong>: No automatic multiplication or % symbol, no locale support</li>
</ul>
<h1 id="limitations">Limitations</h1>
<ul>
<li>Always multiplies by 100 (cannot be disabled)</li>
<li>Always adds trailing % character</li>
<li>Cannot customize the position of the % symbol</li>
<li>Limited control over negative number formatting compared to custom Format strings</li>
<li>Depends on regional settings which may vary across systems</li>
</ul>
<h1 id="regional-settings-impact">Regional Settings Impact</h1>
<p>The appearance of formatted percentages varies by locale:
- <strong>US (English)</strong>: 75.50%
- <strong>European (many)</strong>: 75,50%
- <strong>Switzerland</strong>: 75.50%</p>
<h1 id="related-functions">Related Functions</h1>
<ul>
<li><code>FormatNumber</code> - Formats numbers without percentage conversion</li>
<li><code>FormatCurrency</code> - Formats as currency with symbol</li>
<li><code>Format</code> - General-purpose formatting function</li>
<li><code>CDbl</code> - Converts to Double for percentage calculations</li>
<li><code>Round</code> - Rounds numbers before percentage formatting</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>