問題描述
保持特定位數的簡單 Perl 數學 (simple Perl math while keeping a specific number of digits)
I'm trying to do some simple math like
$example = (12 ‑ 4);
but I need single digit answers to have a 0 in front of them so $example should be
08 not 8
I know I could do something like
if ($example < 10){
$result = "0$example";
}
But I have to think there's a way to specify how many digits you want your output to be when doing simple math like this.
‑‑‑‑‑
參考解法
方法 1:
I recommend saving formatting like this until you print to screen. You can then use printf or sprintf to format the number how you want.
my $example = 12 ‑ 4;
printf("%02d", $example);
Will print:
08
To save it in a string for later use sprintf:
my $example = 12 ‑ 4;
$formatted = sprintf("%02d", $example);
print "$formatted\n";
If you need to fill decimal places use the following:
my $example = 12 ‑ 4;
printf("%0.2f", $example);
will print:
8.00
(by stupidking、Ilion)