|
String Formatting with F$() and Sprintf$() |
When you want to display information on the screen or write it to a file,
the easiest approach is usually the print statement.
Sometimes, however, you do not want to print the information immediately. You may need to build the complete text first so you can place it on a webpage, store it in a database, save it as a note, or pass it to another routine.
In that case, the formatted result needs to be placed into a string variable.
Sheerpower provides two major formatting functions for doing this. The
simplest is f$().
The result is:
Inside an f$() format string, anything between
[[]] is evaluated and inserted into the
resulting string.
Anything that can be used as an expression can appear between the brackets. This includes variables, arithmetic expressions, function calls, string slices, and other expressions whose values can be displayed.
Brackets used inside an expression are balanced normally, so an expression
such as [[name$[1:3]]] works as expected.
Arrays can also be inserted. They are formatted the same way that
print would display them. For example, if
scores contains 90, 85, 77:
A literal [[]] steps over quoted text.
f$()
is treated as program code. It must never contain text from
users or other untrusted sources, because any expression inside
[[...]] can read any variable in scope. This restriction includes templates
loaded from files or database records that can be edited by anyone outside
the development team.
When you need special formatting, such as a fixed number of decimal
places or thousands separators, use sprintf$() inside the
formatted segment.
The expressions are evaluated when f$() runs. This means a
format string stored in a variable can be reused, and each use will insert
the current values of its expressions.
While you are working on a program, it often helps to print a value together
with its name or expression. End a slot with = and f$() writes the
slot's text just as you typed it, then its value:
The result is:
A string is shown between quotes, so blanks at its start or end can be seen:
if city$ is ' Paris ', then [[city$=]]
gives city$=" Paris ". A string that holds a double quote and no
single quote is shown between single quotes instead. When it holds both kinds,
double quotes are used and each double quote inside is written twice, just as it
would be in a program. A number is never quoted. Blanks inside the slot are
kept as typed: [[users]] gives users = 42.
Only an = standing alone at the very end of the slot does this.
Anywhere else, = is the comparison it always is:
[[users]] gives 1. And >=,
<= or an = inside a quoted string are never
mistaken for it.
SPRINTF$()
string$ = sprintf$(string_format$, arg1, arg2, .. )
sprintf$() is a managed, printf-inspired formatting function with
Sheerpower-specific extensions for grouping, dates, pluralization, title
capitalization, positional masks and English number words. Formatting errors
raise exceptions rather than corrupting runtime memory. Applications
must still use explicit monetary rounding where needed.
Output:
Output:
Output:
Output:
Output:
Create Proper English Titles
Titles often follow special capitalization rules. Important words are
capitalized, while smaller connecting words such as
a, an, the,
of, and to may remain lowercase
when they are not the first word. In addition, hundreds of commom special
cases are supported.
The %T format specifier, using a capital
T, formats text using title capitalization.
In the example below, is is capitalized because it is a
verb. In title capitalization, verbs are treated as important words,
even when they are short.
Output:
Output:
Sheerpower supports the %w format for producing the written-in-words version
of a numeric value.
This is especially useful for checks, invoices, receipts, legal documents, and other business output where an amount must appear both numerically and in words.
Problem:
Business software often needs to print monetary amounts in words, such
as "One thousand two hundred thirty four and 56/100".
Solution:
Use the %w format in sprintf$() to convert
a numeric value into its written form.
English whole-number words are followed by a truncated two-digit hundredths fraction. The fractional
portion is produced in check
style as and nn/100.
Efficiency:
By making written-number formatting part of
sprintf$(), Sheerpower eliminates repetitive conversion
code and keeps business formatting fast, consistent, and easy to read.
For example:
Output: 1234.567 Written: One thousand two hundred thirty four and 56/100
This behavior is intentional. A rounded result such as
57/100 would overstate the written amount. For check and
payment text, truncation is the safer and more conventional rule.
Some additional examples:
Output:
Use %w when you want the number written in words. Use
other numeric formats such as %r or %m when
you want conventional numeric display.
Output:
Output:
Output:
Output:
| Combination | Result |
|---|---|
| \b | Backspace |
| \f | Form-feed |
| \n | New line |
| \r | Return |
| \t | Tab |
| \0nnn | Generate a character based on the octal value of nnn For example \0102 >> B |
| \\ | The "\" character |
Output:
sprintf$() conversion formats. Formats
marked SP are Sheerpower extensions (not part of C's printf).
% and the format letter,
and flags may be combined (for example %-8.2f):
| Flag | Meaning | Example → Result |
|---|---|---|
N (a number) | Minimum field width, right-justified | sprintf$('%5i', 42) → 42 |
- | Left-justify within the width | sprintf$('%-5i|', 42) → 42 | |
0 | Pad a number with leading zeros | sprintf$('%05i', 42) → 00042 |
.N | Precision: number of decimal places | sprintf$('%.2f', 3.14159) → 3.14 |
+ | Force a leading + on positive reals (%r/%f/%m; integer formats ignore it) | sprintf$('%+.2f', 42) → +42.00 |
| Format | Meaning | Example → Result |
|---|---|---|
% | General substitution (any type) | sprintf$('%', 99) → 99 |
%s | String (a width justifies it: %-6s left, %6s right) | sprintf$('%s', 'hello') → hello |
%i %d | Integer | sprintf$('%i', 42) → 42 |
%r %f | Real number (.N decimals; + forces a sign) | sprintf$('%.2r', 3.14159) → 3.14 |
%e | Scientific notation | sprintf$('%e', 3.14159) → 3.141590e00 |
%g | Real, compact | sprintf$('%g', 3.14159) → 3.14159 |
%m (SP) | Number with comma grouping (.N decimals) | sprintf$('%.2m', 1234.5) → 1,234.50 |
%o %x %b | Octal, hexadecimal, binary | sprintf$('%x', 123) → 7b |
%c | The character with the given code (like C); given a string, its first character | sprintf$('%c', 66) → B |
%h (SP) | Horizontal tab to a column (argument = the position) | sprintf$('%h%i', 15, 45) → aligns 45 at column 15 |
%p (SP) | Pluralize the following word by the count | sprintf$('% %p', 2, 'item') → 2 items |
%t (SP) | Date/time with @-items (see the Date and Time page) | sprintf$('%t@yyyy', secs) → 2026 |
%T (SP) | Title Case | sprintf$('%T', 'hello world') → Hello World |
%w (SP) | Number written in words (check style) | sprintf$('%w', 1234) → One thousand two hundred thirty four and 00/100 |
%z (SP) | Lay the string into a template: @ takes the next character, [a:b] copies a range (a template must have at least one @ or [a:b]) | sprintf$('%z@@@-@@-@@@@', '123456789') → 123-45-6789 |
%, @, [ and ]%%. A single
% begins a conversion, so an undoubled % with no matching
argument raises an error — always write %%.
Output:
@, [ and ] are ordinary
literals everywhere except inside a %t template (where
@ begins a date/time item) and a %z template (where
@ is a placeholder and [ begins a range). Outside those
two, type them directly:
Output:
@ or [ inside a
%t or %z template, so build any such text outside the
%t/%z part (a separate sprintf$(), or plain
string concatenation).
%z handles string length@ mask, each @ takes the next character of the
string in order:
@s, the extra trailing characters are dropped:
sprintf$('%z@@@', 'hello') → hel.@s, it raises an error ("Not enough data for @ substitutions").[a:b] range copies characters by absolute position and clamps to the
string's length, so a range past the end simply stops at the last character:
sprintf$('%z[1:10]', 'hi') → hi.
%p with more than one count%p pluralizes its word using the most recent
numeric % before it, so several count/word pairs work in one format
string:
Output:
%p, it defaults to the plural form
(sprintf$('%p', 'foot') → feet) — so always give
%p a count.
sprintf$() formats strings using placeholders (%)
and arguments of any data type.%i, %r, %f,
%d) for integers and reals, including decimal rounding with
.n.%p (plurals),
%t (dates/times),
%T (titles),
%w (Numbers as written words),
%z (string substitutions),
%m (money/commas), and
%h (horizontal tabs).%o, %x, and %b.\n, \t, \\, \0nnn).@short can process
10+ million operations per second, ideal for logging.f$() builds formatted strings — text with
expressions embedded right inside it:
f$("{lastname} is {age} years")
|
Hide Description
|
|
|
Enter or modify the code below, and then click on RUN |
|
Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use. |