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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值