sscecina has asked for the wisdom of the Perl Monks concerning the following question:
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.
TIA
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: [s]printf %d oddity
by ikegami (Patriarch) on May 19, 2005 at 22:06 UTC | |
|
Re: [s]printf %d oddity
by Joost (Canon) on May 20, 2005 at 08:46 UTC | |
|
Re: [s]printf %d oddity
by chas (Priest) on May 19, 2005 at 22:15 UTC | |
by astroboy (Chaplain) on May 20, 2005 at 09:36 UTC | |
by Joost (Canon) on May 20, 2005 at 09:45 UTC | |
by astroboy (Chaplain) on May 20, 2005 at 10:13 UTC | |
by Joost (Canon) on May 20, 2005 at 11:45 UTC | |
by Anonymous Monk on May 20, 2005 at 11:24 UTC |