views:

8920

answers:

4

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
+2  A: 

Nevermind, dumb question: you can cast ints in Perl.

int(5/1.5) = 3;
Bryan Denny
Yes, but integer division would be int(5) / int(1.5). Otherwise, you're just rounding the real division.
Rog
but int(5) / int(1.5) != int
Learning
Sorry, this is what I was really asking for. I was wanting an int result after doing any sort of division. So yes, I was looking for rounding.
Bryan Denny
+21  A: 

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
crosstalk
A: 

How to round up?

int(x + .5)

ex: int(1.5 + .5) = int(2) = 2 int(1.6 + .5) = int(2.1) = 2

The old Visual Basic had two functions. INT and FIX. INT took the int of a number by rounding up first. FIX just trunicated off the decimal point.

Now I am finding in javascript and in perl, INT operates how FIX works.

Just remember int(A / X) * X + A % X = A

Anyways,

int(int($a + .5) / int($b + .5))

PS: before doing this trick in a programming language, make sure that the int does not round up first!

A: 

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.

Steve Schaefer