sprintf and printf
sprintf builds a formatted string, and printf prints it directly.
In this page:
sprintf and printf
The format string contains conversion codes such as %s for strings, %d for integers, %f for floating-point numbers and %x for hexadecimal. You can add a width, a precision such as %.2f, a minus sign for left alignment and a 0 for zero padding. printf prints the formatted result, while sprintf returns it so you can store it.
Note:
Write %% to print a literal percent sign.
Example: sprintf and printf
use strict;
use warnings;
my $pi = 3.14159265;
printf "Pi to 2 places: %.2f\n", $pi;
printf "Integer from float: %d\n", 7.9;
printf "Padded: [%5d] [%-5d] [%05d]\n", 42, 42, 42;
printf "Strings: [%8s] [%-8s]\n", "right", "left";
printf "Hex: %x, Octal: %o, Binary: %b\n", 255, 8, 5;
printf "Percent: %d%%\n", 50;
my $row = sprintf("%-10s|%6.1f", "Total", 1234.567);
print "$row\n";
print "Scientific: ", sprintf("%.3e", 12345.678), "\n";
# Output:
# Pi to 2 places: 3.14
# Integer from float: 7
# Padded: [ 42] [42 ] [00042]
# Strings: [ right] [left ]
# Hex: ff, Octal: 10, Binary: 101
# Percent: 50%
# Total |1234.6
# Scientific: 1.235e+04
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Providing fewer arguments than there are conversion codes
- Using %d with a fractional number and expecting rounding
- Forgetting that printf does not add a newline
Chapter Summary
- %s string %d integer %f float
- %.2f sets the precision
- Width and flags align and pad
- sprintf returns and printf prints
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: