in reply to Floating point problems

I agree that it does seem odd that perl apparently uses a different rounding methodology for the int() function versus doing the calculation in print. But, there is no cut and dry way to handle this. sprintf and printf use round half to even. If you want a explanation of all of the different rounding strategies then search wikipedia for round half to even.
foreach my $i (0.5, 1.5, 1.7, 2.3 ,2.5, 2.7){ printf "%2.0f", $i; }
Output: 0 2 2 2 2 3 As you can see, it does round toward even. Here is another example with int() that doesn't work the way you think it would:
print int(0.6/0.2);
You would think the above would print 3, but it prints 2. The following works like you expect and prints 3.
print 0.6/0.2;
The short is that there are several methods for rounding, and you really need to know when and where each method is used or you don't use floating point maths to calculate money until displayed for output. Also, you should read "What Every Computer Scientist Should Know About Floating-Point Arithmetic". You can find it by googling. People have different uses for different rounding schemes, again read about rounding on wikipedia. These different needs means that not all functions will round the same. By the way, this is not just a perl problem/difference.

Replies are listed 'Best First'.
Re^2: Floating point problems
by DoctorBinary (Initiate) on Oct 25, 2010 at 13:09 UTC
    For what it's worth, ActivePerl prints 1 2 2 2 3 3. In other words, it uses "round half away from zero" (languages, and even different compilers and interpreters for the same language, are inconsistent in this regard -- see my article http://www.exploringbinary.com/inconsistent-rounding-of-printed-floating-point-numbers/).