Can anyone shed any light on this (I find the documentation for printf and sprintf to be particularly vague...):

for my $num ( 0 .. 101 ) { $num += 0.005; printf "%.2f\n", $num; }

Output: I get (using ASP 5.61, WinXP):

0.01 1.00 2.00 3.00 .. 8.01 ..

followed by seemingly random series of x.00 or x.01. Interestingly(?), if I change the number of decimals that I want to round to:

for my $num ( 0 .. 101 ) { $num += 0.0005; my $result = sprintf "%.3f", $num; print "$result\n"; }

I get similarly strange results, but not for the same 'numbers' (eg I get 2.001 and 3.001, as compared with 2.00 and 3.00 in the first case

Am I missing something (as usual)?

tia, dave


In reply to (s)printf and rounding woes by Not_a_Number

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.