in reply to How do I print/round a number to a given number of decimal places?
This other answer, by wrvhage, has the great property of working correctly for values like 3.005 rounded to two places (where sprintf is not). However, it needs a couple of tweaks to work for negative numbers.
sub stround { my( $n, $places ) = @_; my $sign = ($n < 0) ? '-' : ''; my $abs = abs $n; $sign . substr( $abs + ( '0.' . '0' x $places . '5' ), 0, $places ++ length(int($abs)) + 1 ); }
|
|---|