Formatting Data with sprintf
The sprintf
function takes the same arguments as printf
(except for the optional filehandle), 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
provides:
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
) uses a leading zero on some of the format numbers, 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 zeroes 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 zeroes, looking 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 is large enough ...
Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.