Unfortunately, using printf numeric formats doesn't interact well with perl's habit of storing things in whatever form it thinks best, be it floating point, integer, or unsigned integer.

Any of the numeric formats will result in a C-level cast into the type specified by the format (though perl will use the correct length modifiers, never casting to int or float when it's using long or double). So %e, %f, and %g cast to a floating point number, potentially losing precision if perl is using 64 bit integer types, while %d, %u, %o, %x can lose precision or range or cast an unsigned to signed or vice versa.

A simple example:

$ perl $x = 2**65; printf("%d\n", $x); __END__ -1
Here, $x is a floating point value. Perl knows you want an integer type, so it tries to convert it, but it's out of range, so UV_MAX is used instead (likely 2**32-1 or 2**64-1) but that is cast to a signed integer type, giving -1.

You're best off sticking to an %s (or %_) format whenever possible.


In reply to Re: sprintf zero-fill issue by ysth
in thread sprintf zero-fill issue by mlong

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.