Ceil/Floor/Round in Perl

pradeep's Avatar author of Ceil/Floor/Round in Perl
This is an article on Ceil/Floor/Round in Perl in Perl.
Rated 3.00 By 4 users

Ceil in Perl



Cieling is basically outputing the next largest integer for an given real number.
Code:
ceiling(x) is the smallest integer not less than x
Ways to do it in Perl, a) using our own logic

Code: Perl
my $num = 45.4;
my $ceil = int($num + 0.99);

b) using POSIX

Code: Perl
use POSIX qw/ceil/;

my $num = 45.4;
my $ceil = ceil($num);

Floor in Perl



Flooring is outputing the next smallest integer for an given real number.
Code:
floor(x) is the largest integer not greater than x
Ways to do it in Perl, a) using our own logic

Code: Perl
my $num = 45.4;
my $floor = int($num);

b) using POSIX

Code: Perl
use POSIX qw/floor/;

my $num = 45.4;
my $floor = floor($num);

Round in perl



Rounding is converting any floating-point number to the nearest integer.

Ways to do it in Perl, a) using our own logic

Code: Perl
my $num = 45.4;
my $round = int($num + 0.5);

b) using Math::Round

Code: Perl
use Math::Round qw/round/;

my $num = 45.4;
my $round = round($num);

It'll be really nice if everyone crontributes to this thread with the equivalent functions in the language they are comfortable with.
shabbir like this
1
sorin25's Avatar, Join Date: Jan 2011
Newbie Member
God dam, how the fuck are you morons still alive ?

PHP Code:
use POSIX qw/ceil/;
sub idiot_ceil { return int($_[0] + 0.99) }

for 
$i qw/0.0005 -1.4 4.00005/) {
     
local $,="\t"local $\="\n";
     print 
$iidiot_ceil($i), ceil($i), (idiot_ceil($i) != ceil($i)) ? " yet again, you are a moron" ".. you got this right genius";

If you morons have trouble running this, this is the output:
Code:
0.0005    0    1     yet again, you are a moron
-1.4    0    -1     yet again, you are a moron
4.00005    4    5     yet again, you are a moron
Fuck, and this is a top Google result. Stop publishing this crap before you infect the rest of the planet with your idiocy!
0
asha's Avatar, Join Date: Nov 2006
Go4Expert Member
Really nice, but the methods using modules is much more reliable I guess.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nomination for Article of the month - Aug 2009 Started.