TExcelTAD
Home › Perl › Formatting with sprintf

Formatting with sprintf

sprintf builds a string from a format and a list of values, exactly like C's function of the same name. printf does the same but prints the result instead of returning it. They are the tools for aligned columns, fixed decimals, padding and number bases.

perl · try it yourself
use strict;
use warnings;

my $item  = "Notebook";
my $qty   = 3;
my $price = 2.5;

my $line = sprintf("%s x %d = %.2f", $item, $qty, $qty * $price);
print "$line\n";
printf "%s costs %.2f each\n", $item, $price;
Notebook x 3 = 7.50
Notebook costs 2.50 each

Each % conversion in the format consumes the next value from the list.

Common conversions

Conversion Meaning sprintf example Result
%s string sprintf "%s!", "hi" hi!
%d integer (truncated) sprintf "%d", 7.9 7
%f floating point (6 decimals) sprintf "%f", 1.5 1.500000
%.2f 2 decimals, rounded sprintf "%.2f", 3.14159 3.14
%e scientific notation sprintf "%.2e", 12345 1.23e+04
%g %f or %e, whichever is shorter sprintf "%g", 0.00001 1e-05
%x %X hexadecimal sprintf "%x", 255 ff
%o octal sprintf "%o", 8 10
%b binary sprintf "%b", 5 101
%% a literal percent sign sprintf "%d%%", 50 50%
perl · try it yourself
use strict;
use warnings;

my $n = 255;
printf "decimal %d, hex %x, HEX %X, octal %o, binary %b\n", ($n) x 5;
printf "%.3f | %.0f | %e | %g\n", 2/3, 2.5, 123456, 0.0001234;
printf "Progress: %d%%\n", 75;
decimal 255, hex ff, HEX FF, octal 377, binary 11111111
0.667 | 2 | 1.234560e+05 | 0.0001234
Progress: 75%

Notice that %.0f turns 2.5 into 2: the C library rounds halves to the nearest even number ("banker's rounding"), and some decimal values are stored slightly below or above their written value. Don't rely on sprintf for financial rounding rules.

Width, alignment and padding

Between % and the letter you can add flags and a width:

Format Meaning Result for 42 / "ab"
%6d right-align in 6 columns 42
%-6d left-align 42
%06d pad with zeros 000042
%+d always show the sign +42
%6s / %-6s same for strings ab / ab
%.1s precision on a string = maximum length a
perl · try it yourself
use strict;
use warnings;

my @rows = (["Coffee", 3, 2.5], ["Croissant", 12, 1.95], ["Juice", 1, 4]);

printf "%-10s %5s %8s\n", "Item", "Qty", "Total";
printf "%s\n", "-" x 25;
for my $r (@rows) {
    my ($name, $qty, $price) = @$r;
    printf "%-10s %5d %8.2f\n", $name, $qty, $qty * $price;
}
printf "Invoice #%06d, change %+.2f\n", 815, -0.5;
Item         Qty    Total
-------------------------
Coffee         3     7.50
Croissant     12    23.40
Juice          1     4.00
Invoice #000815, change -0.50

Width from an argument

Use * to take the width (or .* for the precision) from the argument list. This lets you size columns to fit the data:

perl · try it yourself
use strict;
use warnings;
use List::Util qw(max);

my %score = (Ana => 91, Bartholomew => 78, Li => 85);
my $width = max map { length } keys %score;

for my $name (sort keys %score) {
    printf "%-*s : %3d\n", $width, $name, $score{$name};
}
printf "%.*f\n", 3, 3.14159265;
Ana         :  91
Bartholomew :  78
Li          :  85
3.142

Reordering arguments

An explicit index like %2$s picks a specific argument, which helps when the same value appears twice or when translations reorder words:

perl · try it yourself
use strict;
use warnings;

printf "%1\$s loves %2\$s, and %2\$s loves %1\$s.\n", "Romeo", "Juliet";

my $fmt = '%2$s %1$s';             # single quotes: no interpolation of $s
print sprintf($fmt, "World", "Hello"), "\n";
Romeo loves Juliet, and Juliet loves Romeo.
Hello World

Inside double quotes the $ must be escaped (%1\$s), otherwise Perl would try to interpolate a variable $s. Single-quoted formats avoid that problem.

Commas in large numbers

sprintf has no thousands separator, but a classic regex adds one:

perl · try it yourself
use strict;
use warnings;

sub commify {
    my $text = reverse sprintf("%.2f", shift);
    $text =~ s/(\d{3})(?=\d)/$1,/g;
    return scalar reverse $text;
}

print commify($_), "\n" for 1234567.891, 999, 1000;
1,234,567.89
999.00
1,000.00

The number is reversed so the regex can group digits from the right, then reversed back. (?=\d) is a lookahead: it checks that another digit follows without consuming it.

Test yourself

What does sprintf("%05.1f", 3.14159) return?

  1. 3.1
  2. 003.1
  3. 3.14159
  4. 00003

Which format left-aligns a string in 12 columns?

  1. %12s
  2. %-12s
  3. %s12
  4. %012s

How do you print a literal percent sign with printf?

  1. \%
  2. %%
  3. %p
  4. '%'