in reply to Rounding problem with sprintf??

This is a known "bug". It happens like that in C as well. Write your own rounding function, or use this one:
# round(789.456,-2) => 800 # round(789.456,-1) => 790 # round(789.456) => 789 # round(789.456,1) => 789.5 # round(789.456,2) => 789.46 sub round { my ($n, $p) = @_; my $sign = ($n > 0) ? 1 : -1; $p ||= 0; $n *= 10 ** $p; $n = int($n + .5 * $sign); return $n / 10**$p; }


japhy -- Perl and Regex Hacker

Replies are listed 'Best First'.
Re^2: Rounding problem with sprintf??
by Anonymous Monk on Sep 04, 2014 at 07:26 UTC

    This sub has the same bug as sprintf.

    round(5.245,2) returns 5.25

    but

    round(9.325,2) returns 9.32