Is there more than one function for rounding a
number up in perl?
I tried the ceil() function but get an undefined subroutine
message.
Here is a Perl ceil/floor equivalent. The first code section
seems to correctly implement floor by taking into account that
int() does not use the sign in its process of rounding. The
second code section with floor, although intuitive is not correct.
For a full proof, all the values between 2.0 - 2.9 should be checked.
sln
# ===========================================
# Correct ceil/floor equavelent
# This floor takes the sign into acount
# when rounding.
# - - - - - - - -
use strict;
use warnings;
printf( "The floor of 2.8 is %f\n", _floor( 2.8 ) );
printf( "The floor of -2.8 is %f\n", _floor( -2.8 ) );
printf( "The ceil of 2.8 is %f\n", _ceil( 2.8 ) );
printf( "The ceil of -2.8 is %f\n", _ceil( -2.8 ) );
sub _ceil {return int(shift()+.5)}
sub _floor {my $y = shift(); return int(($y < 0) ? $y-.5 : $y)}
__END__
The floor of 2.8 is 2.000000
The floor of -2.8 is -3.000000
The ceil of 2.8 is 3.000000
The ceil of -2.8 is -2.000000
# ===========================================
# Correct ceil equavelent, incorrect floor
# Int() rounds down the Absolute value.
# So do not use this floor.
# - - - - - - - -
use strict;
use warnings;
printf( "The floor of 2.8 is %f\n", _floor( 2.8 ) );
printf( "The floor of -2.8 is %f\n", _floor( -2.8 ) );
printf( "The ceil of 2.8 is %f\n", _ceil( 2.8 ) );
printf( "The ceil of -2.8 is %f\n", _ceil( -2.8 ) );
sub _ceil {return int(shift()+.5)}
sub _floor {return int(shift())}
__END__
The floor of 2.8 is 2.000000
The floor of -2.8 is -2.000000
The ceil of 2.8 is 3.000000
The ceil of -2.8 is -2.000000
==========================================
C - reference code
// crt_floor.c
// This example displays the largest integers
// less than or equal to the floating-point values 2.8
// and -2.8. It then shows the smallest integers greater
// than or equal to 2.8 and -2.8.
#include <math.h>
#include <stdio.h>
int main( void )
{
double y;
y = floor( 2.8 );
printf( "The floor of 2.8 is %f\n", y );
y = floor( -2.8 );
printf( "The floor of -2.8 is %f\n", y );
y = ceil( 2.8 );
printf( "The ceil of 2.8 is %f\n", y );
y = ceil( -2.8 );
printf( "The ceil of -2.8 is %f\n", y );
}
Output
The floor of 2.8 is 2.000000
The floor of -2.8 is -3.000000
The ceil of 2.8 is 3.000000
The ceil of -2.8 is -2.000000