fnever has asked for the wisdom of the Perl Monks concerning the following question:

after running this simple code under bash:

perl -e 'for($i=0;$i<10;$i+=0.01){print "$i\n"}'


why I (and you guys) will get the following result:
......(ignored)
9.97999999999983
9.98999999999983
9.99999999999983

Replies are listed 'Best First'.
Re: quick question,why int turns to float
by ikegami (Patriarch) on Jun 23, 2009 at 00:38 UTC
    Because 1/10 is a periodic number in binary, it can't be stored exactly by a computer. Either round the number, or work with integers:
    for (0..99) { my $i = $_/100; print("$i\n"); }
Re: quick question,why int turns to float
by toolic (Bishop) on Jun 23, 2009 at 00:32 UTC
    The 2nd iteration through the 'for' loop, $i is set to 0.01, which is a floating point value. If you want to control the output, you can use printf:
    perl -e 'for($i=0;$i<10;$i+=0.01){printf "%.2f\n", $i}' ... 9.97 9.98 9.99
Re: quick question,why int turns to float
by Anonymous Monk on Jun 23, 2009 at 00:45 UTC
Re: quick question,why int turns to float
by fnever (Initiate) on Jun 23, 2009 at 00:48 UTC
    is that mean i should migrate all my codes from "print" to "printf"...? it's tough:(
      i should migrate all my codes from "print" to "printf"...?

      Only those print statements that involve floating-point values, and only when you really care about how the output looks (which probably should be most of the time, when it involves floats).

      As for how tough it is, you only need to fix existing code once, and you'll be better off than you would be if you didn't fix it, don't you think? Also, now you know how to do it right the first time whenever you write new code.