Formatting Data with sprintf
The sprintf function takes
the same arguments as printf (except
for the optional filehandle, of
course), but it returns the requested string instead of printing it.
This is handy if you want to store a formatted string into a variable
for later use, or if you want more control over the result than printf alone would provide:
my $date_tag = sprintf "%4d/%02d/%02d %2d:%02d:%02d", $yr, $mo, $da, $h, $m, $s;
In that example, $date_tag gets
something like "2038/01/19 3:00:08".
The format string (the first argument to sprintf) used a leading zero on some of the
format number, which we didn’t mention when we talked about printf formats in Chapter 5. The leading zero on the format number
means to use leading zeros as needed to make the number as wide as
requested. Without a leading zero in the formats, the resulting
date-and-time string would have unwanted leading spaces instead of
zeros, like "2038/ 1/19 3: 0:
8".
Using sprintf with “Money Numbers”
One popular use for sprintf is when you want to format a number
with a certain number of places after the decimal point, such as when
you want to show an amount of money as 2.50 and not 2.5—and certainly not as 2.49997! That’s easy to accomplish with the
"%.2f" format:
my $money = sprintf "%.2f", 2.49997;
The full implications of rounding are numerous and subtle, but, in most cases, you should keep numbers in memory with all of the available accuracy, rounding off only for output.
If you have a “money number” that may be ...