in reply to Behaviour of int() unexpected

Some people have told you why, but not what to do about it.

In general case of a 32bit float the float has a factor of 23bit accuracy, and since base 10 log of 2^23 = 6.9 digits, it is safe to use 5 digits for yourself, and 1 digit for error.

For example. If you know your numbers are 000.00 to 999.99 then you can simply add 0.001 before you round down (or subtract 0.001 before you round up), then you will never encounter this problem and your numbers will always have their 'ideal' value.

perl -e "my $val = 8.95; printf('%d',int(($val + 0.001) * 100));" 895

If you have 64bit float then its safe to assign 14 digits for yourself and use the 15th for error:

Replies are listed 'Best First'.
Re^2: Behaviour of int() unexpected
by ForgotPasswordAgain (Vicar) on Mar 11, 2025 at 17:45 UTC
    Or use '%.0f' instead of '%d':

    perl -Mstrict -wE'my $val = 8.95; printf("%.0f\n", 100*$val);'

      That rounds rather than truncate.