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
本文介绍Perl中实现舍入、向上取整和向下取整的方法。包括如何使用内置函数创建自定义舍入函数,并介绍了Perl 5中提供的POSIX模块内的floor()和ceil()函数。
3万+

被折叠的 条评论
为什么被折叠?



