方法1: 自己寫 round()
sub round { my $val = shift; my $col = shift; my $r = 10 ** $col; my $a = ($val > 0) ? 0.5 : -0.5; return int($val * $r + $a) / $r; } # 於要取的位數後 +0.5, 再取整數即可. my $a = 10.335444; print round($a, 2);
方法2: 使用 sprintf()
my $a = 10.335444; print sprintf("%.2f", $a);
用法可參考: Perl 5.8.0 Documentation - sprintf