Friday, November 13, 2009

Perl: What is the equivalent of Ceil()


Share at Facebook

Question: At Perl, what is the equivalent function of Ceil? Or how can I perform Ceil on a number like other languages.

Answer: So far, I don't know any function to serve this issue. But if I need, I use sprintf() combined with floating. Below example will show you what exactly I mean for.


my $number = 10.51;
$number = sprintf("%.0f", $number);
print $number;

The above code will output 11, which is the exact ceiling of 10.51.




2 comments:

murphy42 said...

tested and prooved?!? :)

how about:
my $number = 10.03;
$number = sprintf("%.0f", $number);
print $number; # --> 10 ????

so your function is more or less "round", instead you can simply use

print int($number)+1; # -> ceil

or

print int($number+0.5); # --> round

Flier said...

Perl has ceil (and floor) functions in the POSIX standard library module, both of which work with negative numbers.

use POSIX qw(ceil floor);
$number = ceil($number);


For testing any homebrew routines, some correct outputs are:

ceil(-1.4)=-1
floor(-1.4)=-2
ceil(1.4)=2
floor(1.4)=1

ceil(-1.6)=-1
floor(-1.6)=-2
ceil(1.6)=2
floor(1.6)=1