Alex Rivera | Logout

How should I do integer division in Perl?

Asked 2009-02-12T02:44:20.783
66

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
Edit
Report

1 Answer

94

There are at least 2 reasonable answers to this question. (I originally gave only answer 2.)

  1. 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

  2. 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
answered 2009-02-12T02:49:50.413

Your Answer