Perl FAQ 4.13: Does perl have a round function? What about ceil() and floor()?

Perl FAQ 4.13

Does perl have a round function? What about ceil() and floor()?

Perl does not have an explicit round function. However, it is very simple to create a rounding function. Since the int() function simply removes the decimal value and returns the integer portion of a number, you can use

sub round {
    my($number) = shift;
    return int($number + .5);
}

If you examine what this function is doing, you will see that any number greater than .5 will be increased to the next highest integer, and any number less than .5 will remain the current integer, which has the same effect as rounding.

A slightly better solution, one which handles negative numbers as well, might be to change the return (above) to:

    return int($number + .5 * ($number <=> 0));

which will modify the .5 to be either positive or negative, based on the number passed into it.

If you wish to round to a specific significant digit, you can use the printf function (or sprintf, depending upon the situation), which does proper rounding automatically. See the perlfunc man page for more information on the (s)printf function.

Version 5 includes a POSIX module which defines the standard C math library functions, including floor() and ceil(). floor($num) returns the largest integer not greater than $num, while ceil($num) returns the smallest integer not less than $num. For example:

    #!/usr/local/bin/perl
    use POSIX qw(ceil floor);

    $num = 42.4;  # The Answer to the Great Question (on a Pentium)!

    print "Floor returns: ", floor($num), "\n";
    print "Ceil returns:  ", ceil($num), "\n";
Which prints:
    Floor returns: 42
    Ceil returns:  43


Other resources at this site: