in reply to int's behaviour

As swampyankee points out it would appear that although you think you have an integer, in fact you have a floating point number as the internal representation so your 255 is stored as 254.999999 which when you apply int to it gets truncated and results in the behaviour described. Using sprintf instead of int will probably behave as you desire.

$i = sprintf "%.0f", 254.99; print "$i\n"; # printf/sprintf rounds rather than truncates using %f # however %d works just like int() printf "Number %.3f int %d sprintf %.0f\n",$_/7,$_/7,$_/7 for 1..100;

I recommend My floating point comparison does not work. Why ? and particularly the article What Every Scientist Should Know About Floating-Point Arithmetic

Replies are listed 'Best First'.
Re^2: int's behaviour
by kyle (Abbot) on Nov 25, 2007 at 03:12 UTC

    That's a good suggestion, but beware that sprintf uses the round-to-even method of rounding.

    $ perl -e 'printf "%.0f\n", 2.5;' 2 $ perl -e 'printf "%.0f\n", 1.5;' 2

    To get the usual "round up" method, I usually use int with the value plus a half.

    $ perl -le '$x=1.5;print int($x+.5)'; 2 $ perl -le '$x=2.5;print int($x+.5)'; 3