Rounding and int
Came across a curious fact today. Try this out:
$ perl -e "print int(2.07 * 100)"
You get 206 not 207. Same rounding down happens with 2.01 2.03 and 2.05. As perldoc -f int says,
You should not use this function for rounding
One alternative is to use sprintf, for instance:
my $num = sprintf("%.0f",(2.07 * 100)); # returns 207 Or even, from the command line:
perl -e 'printf("%.0f",(2.07 * 100))' # returns 207
Or you could use Math::Round and let that do the thinking for you. ;)
0 TrackBacks
Listed below are links to blogs that reference this entry: Rounding and int.
TrackBack URL for this entry: http://www.robbiebow.co.uk/mt/mt-tb.cgi/49

Yes, floating point numbers have a habit of naughtiness. I think I learned little else I still consider relevant from low-level programming.
Of course, Perl programmers should use CPAN's Math::* libraries for better precision.
I note your example uses 2 decimal places and I know what you do for a living. I prefer to store prices in pence, or the equivalent in whatever currency you use, instead of pounds, to avoid problems like this.
But then you get products that people typically buy in bulk with a unit cost of less than 1p, such as those electrical components we made a site for a couple of years ago.
Tough life programming, innit?
Happy birthday, belatedly, too.
Storing in minor units is indeed optimal. Receiving data in minor units would be nice as well. Having all currencies adopt the sensible approach of the Japanese Yen which has no minor units at all would be the best approach, albeit not the cheapest.
Ta for the birthday wishes. I make good my threat to visit you sometime soon, mark my words.