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

Hello monks!

I want to know if there's a way to round numbers in perl! like, if its 5.2 - be able to round it down or up.

5.2 -> 5 #(down)
5.2 -> 6 #(up)

Replies are listed 'Best First'.
Re: round numbers
by husoft (Monk) on Oct 07, 2002 at 16:17 UTC
    You can use the Posix module:
    use POSIX; print floor(5.2); #5 print ceil(5.2); #6
Re: round numbers
by zigdon (Deacon) on Oct 07, 2002 at 16:20 UTC

    You could use POSIX, like husoft suggested, or use int:

    $num = 5.2; if ($num > 0) { $floor = int($num); $ceil = int($num) == $num ? $num : int($num)+1; } else { $floor = int($num) == $num ? $num : int($num)-1; $ceil = int($num); }

    Updated: updated to deal with negative numbers correctly, as rir pointed out.

    -- Dan

      Wrong for numbers under 0.
Re: round numbers
by BrowserUk (Patriarch) on Oct 07, 2002 at 16:22 UTC

    The POSIX module is part of the standard distribution and has both ceil and floor() functions.

    #! perl -sw use strict; use POSIX; my $n = 5.2; print $n, ' ', POSIX::ceil($n), ' ', POSIX::floor($n), $/; __DATA__ C:\test>203372 5.2 6 5 C:\test>

    Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!