in reply to Preferred Methods

Well, that only rounds properly for positive numbers.
sub round { my $n = shift; int($n + .5 * ($n < 0 ? -1 : 1)); }
Then you might want to be able to round to a specific place:
sub round { my ($n, $p) = @_; $p ||= 0; # default to integer rounding int($n * 10**$p + .5 * ($n < 0 ? -1 : 1)) / 10**$p; }
Ta da. Now you can round 123.45678 to 123.457 by calling round(123.45678, 3), and you can round 123456789 to 123500000 by calling round(123456789, -5).

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Replies are listed 'Best First'.
Re: Re: Preferred Methods
by theorbtwo (Prior) on Jan 14, 2002 at 22:31 UTC

    I like your round() function, though I'd have it take a "nearest x" parameter instead of a "number of digits" parameter. Just replace the ||=0 with ||=1 and 10**$p with $p. Then you can say round($inches, 1/8), or round($bagles, 12).

    Thanks,
    James Mastros,
    Just Another Perl Scribe