Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I do integer division in Perl?

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 
like image 938
Bryan Denny Avatar asked Feb 12 '09 02:02

Bryan Denny


People also ask

How do I get the remainder in Perl?

When you divide an integer by 2, you get a remainder of 0 (if the number is even) or 1 (if the number is odd). my $is_odd = $num % 2; In general, the modulus will give you an integer between 0 and one less than the right-hand operand in the expression.

Why is integer division used?

Integer division ( // ) The integer division operation // is used when you want your answer to be in whole numbers. Since it is very common for the result of dividing two integers to be a decimal value, in Python3 integers, division rounds the result to the lower bound.

How do you round to 2 decimal places in Perl?

Solution. Use the Perl function sprintf, or printf if you're just trying to produce output: # round off to two places $rounded = sprintf("%. 2f"", $unrounded);


2 Answers

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 
like image 181
Michael Ratanapintha Avatar answered Oct 15 '22 21:10

Michael Ratanapintha


You can cast ints in Perl:

int(5/1.5) = 3; 
like image 29
Bryan Denny Avatar answered Oct 15 '22 19:10

Bryan Denny