Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单的Perl数学,同时保留特定的位数_Perl_Math - Fatal编程技术网

简单的Perl数学,同时保留特定的位数

简单的Perl数学,同时保留特定的位数,perl,math,Perl,Math,我试着做一些简单的数学,比如 $example = (12 - 4); 但我需要一位数的答案,前面有一个0,所以$example应该是 08 not 8 我知道我可以做类似的事情 if ($example < 10){ $result = "0$example"; } if($example

我试着做一些简单的数学,比如

$example = (12 - 4);
但我需要一位数的答案,前面有一个0,所以$example应该是

08 not 8    
我知道我可以做类似的事情

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

但我认为有一种方法可以指定在进行类似这样的简单数学运算时希望输出的位数。

我建议在打印到屏幕之前保存格式设置。然后,您可以使用printf或sprintf来设置所需的数字格式

my $example = 12 - 4;
printf("%02d", $example);
将打印:

08
8.00
要将其保存为字符串供以后使用,请使用sprintf:

my $example = 12 - 4;
$formatted = sprintf("%02d", $example);

print "$formatted\n";
如果需要填写小数位,请使用以下内容:

my $example = 12 - 4;
printf("%0.2f", $example);
将打印:

08
8.00

谢谢你的帮助,sprintf正是我所需要的!