int 
int EXPR
intThis function returns the integer portion of
EXPR. If you’re a C programmer, you’re apt to
forget to use int with division,
which is a floating-point operation in Perl:
$average_age = 939/16; # yields 58.6875 (58 in C) $average_age = int 939/16; # yields 58
You should not use this function for generic rounding, because it
truncates toward 0 and because machine representations of floating-point
numbers can produce counterintuitive results. For example, int(–6.725/0.025) produces –268 rather than the correct –269; that’s because the value is really more
like –268.99999999999994315658.
Usually, the sprintf, printf, or the POSIX::floor and POSIX::ceil functions will serve you better
than will int.
$n = sprintf("%.0f", $f); # round (not trunc) to nearest integerTo compensate for the inherent bias that always rounding a 5 up would cause, IEEE specifies that rounding be toward the nearest even number on a 5. Therefore, this:
for (–3 ... 3) { printf "%.0f\n", $_ + 0.5 }Prints the sequence ‒2, ‒2, ‒0, 0, 2, 2, and 4.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access