I'm trying to understand (for my own sanity - and others I work with) why the following snippet does what it does:
my $x = 8.78; my $y = $x * 100; my $z = $x * 1000; printf "%08d\n", $y; # prints 00000877 - wrong printf "%08d\n", "$y"; # prints 00000878 - right printf "%3.5f\n", $y; # prints 878.00000 - right printf "%08d\n", $z; # prints 00008780 - right
I can understand that since $y is a floating-point number it might be stored in memory as 877.99999999999... But, if so, why doesn't the %3.5f example print 877.99999? And why does multiplying by 1000 make a difference for the %08d version?
I've tested this code on version 5.005_2 on aix, 5.8.6 on win32, and 5.8.4 on linux. Also, I know that the simple "fix" is to convert it to a string first (as in the 2nd printf). 8.78 seems to be one of the magic numbers that triggers this phenomenon. Most do not. I'm sure that there are others... I'd just like to better understand what's happening.
TIAIn reply to [s]printf %d oddity by sscecina
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |