royalanjr has asked for the wisdom of the Perl Monks concerning the following question:

Is there a function to round a number?

Replies are listed 'Best First'.
Re: Rounding function
by vroom (His Eminence) on Apr 25, 2000 at 00:30 UTC
Re: Rounding function
by btrott (Parson) on Apr 25, 2000 at 00:22 UTC
Re: Rounding function
by wrvhage (Sexton) on Apr 17, 2002 at 13:24 UTC
    I pulled this one out of my bag of holding today...
    sub round {
        my ($number,$decimals) = @_;
        return substr($number+("0." . "0" x $decimals . "5"),
                      0, $decimals+length(int($number))+1);
    }
    
    brother Willem

    --
    wrvhage@science.uva.nl.nl | http://www.xs4all.nl/~wrvh
      I'm a complete amateur trying to teach myself to program. After two days of scouring the Camel and Llama books (nobody tell merlyn), your subroutine was exactly what I wanted. I should have checked the monks first. Thank you for this.
        It is amazing to me that this type of function is not built in. I just wanted to thank you for sharing. This simple yet obvious solution is great. Thanks again and God bless, -David
RE: Rounding function
by royalanjr (Chaplain) on Apr 25, 2000 at 00:35 UTC
    Thanks for the answers! I obviously did not really understand what sprintf did.

      One quick place to look for information on *printf is man 3 printf. It's the C manpage on printf, but perl implements it more or less just like in C. You'll probably find it very helpful in the future for printing anything in the format you like.

      I think I'll write a comprehensive tutorial on *printf at some point, unless someone knows about a good one already out there. At least in my version of perldocs, the printf page just says 'just like in C'.