Simple Perl math while storing a certain number of digits

I'm trying to do some simple math like

$example = (12 - 4);

but I need unambiguous answers to have 0 in front of them, so $ example should be

08 not 8    

I know I can do something like

if ($example < 10){
    $result = "0$example";
}

But I have to think that there is a way to indicate how many numbers you want your output to be when you do simple math like this.

+3
source share
1 answer

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
+11
source

All Articles