How should I do integer division in Perl?

What is a good way to always perform integer division in Perl?

For example, I want:

real / int = int int / real = int int / int = int 
+46
perl integer-division
Feb 12 '09 at 2:44
source share
6 answers

You can use ints in Perl:

 int(5/1.5) = 3; 
+35
Feb 12 '09 at 2:47
source share

The lexically limited 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 
+74
Feb 12 '09 at 2:49
source share

int(x+.5) rounds positive values ​​to the nearest integer. Rounding is harder.

To round to zero:

int($x)

In the solutions below, include the following statement:

use POSIX;

To round: POSIX::floor($x)

To round: POSIX::ceil($x)

To round from zero: POSIX::floor($x) - int($x) + POSIX::ceil($x)

To round to the nearest integer: POSIX::floor($x+.5)

Note that int($x+.5) does not work well for negative values. int(-2.1+.5) is equal to int(-1.6) , which is -1.

+4
Dec 14 '09 at 20:07
source share

You can:

 use integer; 

This is explained by Michael Ratanapinat or used manually:

 $a=3.7; $b=2.1; $c=int(int($a)/int($b)); 

notification, 'int' is not executed. it is a function to convert a number to integer form. this is because Perl 5 does not have a separate integer division. The exception is when you use an integer. Then you will lose the real division.

+3
Sep 25 '13 at 9:59 on
source share

Hope this works.

int (9/4) = 2.

Thanks Manojkumar

0
Aug 6 '13 at 13:29
source share

Eg 9/4 = 2.25

int (9) / int (4) = 2

9/4 - remainder / denimator = 2

9/4 - 9% 4/4 = 2

-one
May 05 '11 at 1:54 am
source share



All Articles