www.fachtnaroe.ie



Web This site

Formatting Numeric Output

Dividing your output into format and content

When you want to apply specific formatting to your output you may find that the simple print command will not suffice. If is a rudimentary all-round output statment that offers no guarantee except to get your output on screen. For more fancy numeric output it may not be sufficient; as an example the value 2.90 will probably be displayed as 2.9 on screen as the digit 0 at the end is not significant. If you don't know what significant means then think back to your maths where the concept of significant digits comes from. To get the last digit (the insignificant 0) to appear you need to split your output from the desired format, put them both in a special printf statement and continue otherwise as usual.
  $amount=2.90
  print "Amount = $amount"; # this will display 2.9
  printf "Amount = %3.2f", $amount; # this will display 2.90
  
Try the code above to see how the formatting works. Generally we understand printf to operate like this:
printf "formatting instructions", list, of, output, data...
This is a table that shows some of the formatting codes. Note they all start with a % and end with the relevant code.
%%a percent sign
%ca character with the given number
%sa string
%da signed integer, in decimal
%uan unsigned integer, in decimal
%oan unsigned integer, in octal
%xan unsigned integer, in hexadecimal
%ea floating-point number, in scientific notation
%fa floating-point number, in fixed decimal notation
%ga floating-point number, in %e or %f notation

Last updated: 20120108-18:21
back to top
Fachtna Roe, Senior College, Central Technical Institute, Clonmel, Ireland.