Printf Functions



Printf Functions

  • The print function is a “formatted print” and allows better control of the output from a print statement.


printf format, list;

  • where format is the format specifier and list is what is to be formatted.
  • The format specifiers for printf have the general format of:


  • where % is the identifier used for a specifier, – is an optional minus sign used for justification,
  • w is the width of the field, the period is an optional part followed by the number of decimals, and l is the field type.
  • The field type must be specified.

Examples are:

%20s %



Field Type:

  • The most common field types for the printf statement are:

c   character

s   string

d   integer number (no fraction)

f    floating number

  • There are some other field types, but they are rarely used in programming.
  • To display the variable $num1 with 3 digits total, two to the right of the decimal, you would use a printf like this:

printf “%3.2f”, $var1;

  • To print leading zeros if the number does not have enough digits, add a zero in front of the width:

printf “%03.2f”, $var1;

Field Type:

  • Strings can be displayed with format specifiers, too:

printf “%10s”, “Sachin”; # This will right-justify Sachin into a fiel 10 characters wide.

  • To left-justify a string, use a minus sign in front of the specifier:

printf “%-10s”, “Sachin”;

For Multiple Variable:

  • If you are displaying more than one value, you need a format specifier for each. They are read from left to right:

printf “%6d %5.4f %3d”,$x1,$x2,$x3;

  • The format specifiers are matched up with the variables in order. Multiple format specifiers can be inside the quotations marks, as can any string:

printf “Total is %8.4f”, $total;




Leave a Reply

Your email address will not be published. Required fields are marked *