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

In reply to [s]printf %d oddity by sscecina

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.