What is a good way to always do integer division in Perl?
For example, I want:
real / int = int
int / real = int
int / int = int
There are at least 2 reasonable answers to this question. (I originally gave only answer 2.)
Use the int()
function to truncate the floating-point calculation result to an integer (throwing away the decimal part), as Bryan suggested in his self-answer: #539805
Use the use integer
pragma to make Perl truncate both the inputs and results of calculations to integers. It's scoped to within { }
blocks.
Examples:
print 3.0/2.1 . "\n"; # => 1.42857142857143
print 5.0/1.5 . "\n"; # => 3.33333333333333
print int(3.0/2.1) . "\n"; # => 1
print int(5.0/1.5) . "\n"; # => 3
{
use integer;
print 3.0/2.1 . "\n"; # => 1
print 5.0/1.5 . "\n"; # => 5 (because 1.5 was truncated to 1)
}
print 3.0/2.1 . "\n"; # => 1.42857142857143 again
You can cast ints in Perl:
int(5/1.5) = 3;
int(-6.725/0.025)
is -268 and POSIX::floor(-6.725/0.025)
is -269 see perldoc
int(x+.5)
will round positive values toward the nearest integer. Rounding up is harder.
To round toward zero:
int($x)
For the solutions below, include the following statement:
use POSIX;
To round down: POSIX::floor($x)
To round up: POSIX::ceil($x)
To round away from zero: POSIX::floor($x) - int($x) + POSIX::ceil($x)
To round off to the nearest integer: POSIX::floor($x+.5)
Note that int($x+.5)
fails badly for negative values. int(-2.1+.5)
is int(-1.6)
, which is -1.
int
rounds toward zero, while normal rounding it toward even. Run perl -le 'printf "int(%s) is %d, round(%s) is %.0f;\n", ($_+0.5)x4 for -10..10'
and you will see things like int(-3.5) is -3, round(-3.5) is -4; int(-2.5) is -2, round(-2.5) is -2; int(-1.5) is -1, round(-1.5) is -2; int(-0.5) is 0, round(-0.5) is -0; int(0.5) is 0, round(0.5) is 0; int(1.5) is 1, round(1.5) is 2; int(2.5) is 2, round(2.5) is 2; int(3.5) is 3, round(3.5) is 4; int(4.5) is 4, round(4.5) is 4;
you can:
use integer;
it is explained by Michael Ratanapintha or else use manually:
$a=3.7;
$b=2.1;
$c=int(int($a)/int($b));
notice, 'int' is not casting. this is function for converting number to integer form. this is because Perl 5 does not have separate integer division. exception is when you 'use integer'. Then you will lose real division.
Integer division $x divided by $y ...
$z = -1 & $x / $y
How does it work?
$x / $y
return the floating point division
&
perform a bit-wise AND
-1
stands for
&HFFFFFFFF
for the largest integer ... whence
$z = -1 & $x / $y
gives the integer division ...
perl -E 'my($x,$y)=(-12,4); my $z = -1 & $x/$y; say int($x/$y); say $x/$y; say $z;'
will give: -3, -3, 18446744073709551613.
Eg 9 / 4 = 2.25
int(9) / int(4) = 2
9 / 4 - remainder / deniminator = 2
9 /4 - 9 % 4 / 4 = 2