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:
| %% | a percent sign |
| %c | a character with the given number |
| %s | a string |
| %d | a signed integer, in decimal |
| %u | an unsigned integer, in decimal |
| %o | an unsigned integer, in octal |
| %x | an unsigned integer, in hexadecimal |
| %e | a floating-point number, in scientific notation |
| %f | a floating-point number, in fixed decimal notation |
| %g | a floating-point number, in %e or %f notation |