I recommend that you keep formatting until you print to the screen. Then you can use printf or sprintf to format the number as you want.
my $example = 12 - 4;
printf("%02d", $example);
It will be printed:
08
To save it in a string for later use by sprintf:
my $example = 12 - 4;
$formatted = sprintf("%02d", $example);
print "$formatted\n";
If you need to fill in decimal places, use the following:
my $example = 12 - 4;
printf("%0.2f", $example);
will print:
8.00
source
share