How should I do integer division in Perl?
-
22-08-2019 - |
Question
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
Solution 2
You can cast ints in Perl:
int(5/1.5) = 3;
OTHER TIPS
The lexically scoped integer
pragma forces Perl to use integer arithmetic in its scope:
print 3.0/2.1 . "\n"; # => 1.42857142857143
{
use integer;
print 3.0/2.1 . "\n"; # => 1
}
print 3.0/2.1 . "\n"; # => 1.42857142857143
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.
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.
Hope it works
int(9/4) = 2.
Thanks Manojkumar
Eg 9 / 4 = 2.25
int(9) / int(4) = 2
9 / 4 - remainder / deniminator = 2
9 /4 - 9 % 4 / 4 = 2