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
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.
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.
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);
There are at least 2 reasonable answers to this question. (I originally gave only answer 2.)
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
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
You can cast ints in Perl:
int(5/1.5) = 3;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With