1. Perl
  2. builtin functions
  3. here

sprintf function - string formatting

You can use the sprintf function to create a formatted string. It is convenient to use the sprintf function when you want to fill the left side of number with 0 and output it, or when you want to specify a small number of floating point digits.

my $str = sprintf("%08d", $num1);
my $str = sprintf("%.2f", $num2);
my $str = sprintf("aiueo%08daiueo%.2f", $num1, $num2);

You may want to output numbers or strings according to certain rules. For example, if you want to create a fixed-length string with the missing parts filled with blanks, it is troublesome to create blanks like "18 & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;".

You can convert "18" to "18 & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;" by specifying the format with the sprintf function.

Also, for example, you can output a numerical value with the missing part filled with 0s. 18 can be '00000018'.

You can also output by rounding the decimal point to a certain digit. You can round 12.3456 to one decimal place to get '12.3'.

Format specification description method

my $str = sprintf("%08d", $num1);
my $str = sprintf("%.2f", $num2);
my $str = sprintf("aiueo%08daiueo%.2f", $num1, $num2);

Formatting starts with%. It ends with a fixed alphanumeric character such as d or f. d means to interpret the second argument as an integer, and f means to interpret it as a floating point number.

Specifies the format in which the string is created between the%and the alphabet. "%08d" is read as "Interpret $num1 as an integer and pad it with 0 if it is less than 8 characters". "%.2f" is read as "Interpret $num2 as a floating point number and round it to two decimal places."

List of format specifiers for sprintf function

There are various formatting specifiers for the sprintf function. I created a list.

%c

%c is a format specifier that converts to the character corresponding to the ASCII character code.

%s

%s is a format specifier that interprets the argument as a string. If there is a leading 0 like '002', it will be '002' as a string as it is.

%d

%d interprets the argument as a signed integer. For example, if you pass '0003', it will be converted to 3 because it is 3 in terms of numbers.

%u

%u interprets the argument as a positive integer.

%o

%o interprets the argument as a positive integer and converts it to an octal string.

%x%X

%x interprets the argument as a positive integer and converts it to a hexadecimal string. The notation is lowercase for%x and uppercase for%X.

%b

%b interprets the argument as a positive integer and converts it to a binary string.

%f

%f interprets the argument as floating point.

%e%E

%e is the same as%f, but it formats it in exponential notation. The notation is lowercase for%e and uppercase for%E.

%g%G

%g interprets the argument as floating point and formats it to%e or%f. If the decimal point is short, it will be in the%f format, and if it is long, it will be in the%e format.

Also, unlike%f and%e,%g does not have an extra 0 at the end.

%p

You can get the memory address of the variable given as an argument by%p in hexadecimal notation.

Format to a fixed length string

To format a fixed-length string with the sprintf function, use a format specification like the example below.

%5s Right-justified space filling
%-5s Left-justified space filling
%0s 0 fill

To format a fixed-length string with the sprintf function, write a number after%. Write as%5s.

The default is right-justified space filling. To left justify, add a minus (-) in front of the number to make it like%-5s. To fill in the missing parts with 0, write as%05s.

If the formatted string exceeds the specified string, it will not be truncated and the specification will be ignored.

Format binary, octal, and hexadecimal numbers in base notation

# When expressing binary, octal, and hexadecimal numbers as numeric literals, they are expressed with 0b, 0, and 0X. Use the symbol to format binary, octal, and hexadecimal numbers into this representation.

sprintf("1:% # o", 8);
sprintf("2:% # x", 255);
sprintf("3:% # X", 255);
sprintf("4:% # b", 4);

# Use to format in base notation.

It can also be combined with other formats.

# Convert decimal to octal Fill space with left justification
$formatted[5] = sprintf("1: <%-# 5o>", 8);

# Is classified as a "flag" in the format specification. —— Is also classified as a “flag”. 5 is categorized as what is called "string width".

The order of the "flags" can be anything, but the "flags" must come before the "string width".

"%-# 5o" # OK
# "% -5o" # OK
# "% 5- o" # No

Specify the precision with the number of digits after the decimal point

To specify the precision with the number of decimal places using the sprintf function, use the format specifier%f and the "precision" notation, such as .5.10.

# 3rd place after the decimal point
$formatted[1] = sprintf("%.3f", 0.45674);

To specify the precision with the number of decimal places, use the format specifier%f, which interprets the argument as a floating point number, and the "precision" notation, such as .5.10. If it is .3, it will be rounded to the third decimal place.

It can also be combined with other formats.

# Round to the third decimal place with a character width of 10 that fills the left-justified space
$formatted[2] = sprintf("<% -10.3f>", 0.45674);
  • Is categorized as what is called a "flag". 10 is categorized as what is called "string width". .3 is categorized as what is called "precision". f doesn't seem to have an official name, but here we call it a format specifier.

The order of format specification is

%Flag String Width Precision Format Specifier

Must be. "Flag", "Character string", and "Precision" are format specification options and can be specified as necessary.

Specify the precision by the number of significant digits

To specify precision by significant digits using the sprintf function, use the format specifier%g and the "precision" notation, such as .5.10.

# 3 significant digits
my $formatted = sprintf("%.3g", 45.674);

To specify the precision with the number of decimal places, use the format specifier%g, which interprets the argument as a floating point number, and the "precision" notation, such as .5.10. If it is%.3g, it will be rounded to 3 digits.

Example sprintf function

This is an example of the sprintf function.

A simple example of sprintf

A simple example of the sprintf function.

use strict;
use warnings;

my $num1 = 3;

# Fill in the missing part with 8 digits with 0
my $formatted1 = sprintf("%08d", $num1);
print $formatted1. "\n\n";

# Round to two decimal places
my $num2 = 3.1415;
my $formatted2 = sprintf("%.2f", $num2);
print $formatted2. "\n\n";

# Specify multiple arguments
my $formatted3 = sprintf("aiueo%08daiueo%.2f", $num1, $num2);
print $formatted3 . "\n";

Examples of various formatting

Examples of various formatting.

use strict;
use warnings;

print "(1) List of format specifiers\n";
my @formated;

# 65 is ASC
'A' in II code
$formatted[1] = sprintf("1:%c", 65);

# Interpreted as a string
$formatted[2] = sprintf("2:%s", '00002');

# Interpreted as a signed integer
$formatted[3] = sprintf("3:%d", '-00002');

# Interpreted as an unsigned integer
$formatted[4] = sprintf("4:%u", '00002');

# Convert decimal to octal
$formatted[5] = sprintf("5:%o", 8);

# Convert decimal to hexadecimal (lowercase)
$formatted[6] = sprintf("6:%x", 255);

# Convert decimal to hexadecimal (uppercase)
$formatted[7] = sprintf("7:%X", 255);

# Convert decimal to binary
$formatted[8] = sprintf("8:%b", 4);

# Interpreted as a floating minority point
$formatted[9] = sprintf("9:%f", 0.00004560);

# Interpreted as floating point
# (Lowercase exponential notation)
$formatted[10] = sprintf("10:%e", 0.00004560);

# Interpreted as floating point
# (Capital notation)
$formatted[11] = sprintf("11:%E", 0.00004560);

# Interpreted as floating point
# (End 0 is deleted)
$formatted[12] = sprintf("12:%g", 0.00004560);

# Interpreted as floating point
# (The trailing 0 is removed. Uppercase)
$formatted[13] = sprintf("13:%G", 0.00004560);

# $Num's in-memory address
my $num = 3;
$formatted[14] = sprintf("14:%p", $num);

for my $i (1 .. 14) {
  print $formatted[$i] . "\n";
}

Format to a fixed length string

This is an example to format to a fixed length string using the sprintf function.

use strict;
use warnings;

print "(1) Format to a fixed-length string.\n";
my @formated;

# Fill right-justified space
$formatted[1] = sprintf("1:%5s", 1);

# Fill left-justified space
$formatted[2] = sprintf("2:%-5s", 1);

# 0 fill
$formatted[3] = sprintf("3:%05s", 1);

# Ignored if the specified character length is exceeded
$formatted[4] = sprintf("4:%5d", 123456);

# Other than %s is OK.
$formatted[5] = sprintf("5:%5d", 1);

# Other than %s is OK.
$formatted[6] = sprintf("6:%5g", 1.23);

for my $i (1 .. 6) {
  print $formatted[$i] . "\n";
}

Format binary, octal, and hexadecimal numbers in base notation

This is an example to format binary, octal, and hexadecimal numbers in binary notation with sprintf.

use strict;
use warnings;

print "(1) Format binary, octal, and hexadecimal numbers in the base number table\n";
my @formated;

# Convert decimal to octal
$formatted[1] = sprintf("1:% # o", 8);

# Convert decimal to hexadecimal (lowercase)
$formatted[2] = sprintf("2:% # x", 255);

# Convert decimal to hexadecimal (uppercase)
$formatted[3] = sprintf("3:% # X", 255);

# Convert decimal to binary
$formatted[4] = sprintf("4:% # b", 4);

for my $i (1 .. 4) {
  print $formatted[$i] . "\n";
}
print "\n";

# Convert decimal to octal Fill space with left justification
print "(2) Combine with other formats.\n";
$formatted[5] = sprintf("1: <%-# 5o>", 8);

print $formatted[5] . "\n";

Specify the precision with the number of digits after the decimal point

This is an example that specifies the precision with the number of digits after the decimal point.

use strict;
use warnings;

printf "(1) Specify the precision with the number of digits after the decimal point.\n";
my @formated;
# With precision up to 3 decimal places
# Format.
$formatted[1] = sprintf("%.3f", 0.45674);
print $formatted[1]. "\n\n";

# Round to the third decimal place with a character width of 10 that fills the left-justified space
print "(2) Combine with other formats.\n";
$formatted[2] = sprintf("<% -10.3f>", 0.45674);
print $formatted[2] . "\n";

Specify precision by the number of significant digits

This is an example that specifies the precision by the number of significant digits.

use strict;
use warnings;

printf "(1) Specify the precision by the number of significant digits.\n";

# Format with a precision of 3 significant digits.
my $formatted = sprintf("%.3g", 45.674);
print $formatted . "\n";

Related Informatrion