直接使用以下内容:
my $s = sprintf('%.3f', $f); $s =~ s/\.?0*$//; print $s
...或者定义一个子程序来更一般地执行它:
sub fstr { my ($value,$precision) = @_; $precision ||= 3; my $s = sprintf("%.${precision}f", $value); $s =~ s/\.?0*$//; $s } print fstr(0) . "\n"; print fstr(1) . "\n"; print fstr(1.1) . "\n"; print fstr(1.12) . "\n"; print fstr(1.123) . "\n"; print fstr(1.12345) . "\n"; print fstr(1.12345, 2) . "\n"; print fstr(1.12345, 10) . "\n";
打印:
0 1 1.1 1.12 1.123 1.123 1.12 1.12345