Page 131 - Beginning PHP 5.3
P. 131
Chapter 5: Strings
Specifying Number Precision
When displaying floating - point numbers with the f or F type specifier, you can use a precision specifier to
indicate how many decimal places to round the number to. To add a precision specifier, insert a period
( . ), followed by the number of decimal places to use, before the type specifier:
printf( “%f < br / > ”, 123.4567 ); // Displays “123.456700” (default precision)
printf( “%.2f < br / > ”, 123.4567 ); // Displays “123.46”
printf( “%.0f < br / > ”, 123.4567 ); // Displays “123”
printf( “%.10f < br / > ”, 123.4567 ); // Displays “123.4567000000”
You can use a padding specifier with a precision specifier, in which case the entire number is padded to
the required length (including the digits after the decimal point, as well as the decimal point itself):
echo “ < pre > ”;
printf( “%.2f < br / > ”, 123.4567 ); // Displays “123.46”
printf( “%012.2f < br / > ”, 123.4567 ); // Displays “000000123.46”
printf( “%12.4f < br / > ”, 123.4567 ); // Displays “ 123.4567”
echo “ < /pre > ”;
By the way, if you use a precision specifier when formatting a string, printf() truncates the string to
that many characters:
printf( “%.8s\n”, “Hello, world!” ); // Displays “Hello, w”
Swapping Arguments
As you ’ ve probably noticed, the order of the additional arguments passed to printf() must match the
order of the conversion specifications within the format string. Normally this isn ’ t a problem, but
occasionally you might need to change the order of the conversion specifications without being able to
change the order of the arguments.
For example, say your format string is stored in a separate text file, rather than being embedded in your
PHP code. This is handy if you want to change the way your script displays its output — for example, if
you ’ re creating a different “ skin ” for your application, or if you ’ re creating English, French, and German
versions of your application. Imagine the following format string is saved in a file called template.txt :
You have %d messages in your %s, of which %d are unread.
Your PHP code might then use this template.txt file to display a message to a user as follows (in a
real - world application the $mailbox , $totalMessages , and $unreadMessages values would probably
be pulled from a database):
$mailbox = “Inbox”;
$totalMessages = 36;
$unreadMessages = 4;
printf( file_get_contents( “template.txt” ), $totalMessages, $mailbox,
$unreadMessages );
This code would display the following message:
You have 36 messages in your Inbox, of which 4 are unread.
93
9/21/09 8:53:47 AM
c05.indd 93
c05.indd 93 9/21/09 8:53:47 AM