There's more than one way to do things PerlMonks

### Comment on

 Need Help??

The problem is NOT that printf is stupid.

Yes, if you implement your own "round to 2 decimal places" algorithm that doesn't actually round but instead truncates, then you'll (often) get a different answer than if you actually round (whether or not you use sprintf to actually round, which is one of the better choices available).

Specifically round arithmetically using your own rules and you should at least get consistent results.

See, that just proves that you didn't learn the lesson that a bunch of the other replies in this thread were trying to teach.

sub consistentlyRound { my( \$w ) = @_; my \$p = int( (\$w+0.005)*100 ); return \$p/100; } my \$x = 0.015; my \$y = 0.0001; \$y += 0.0001 for 1..149; print "x=\$x y=\$y\n"; printf "x~%.2f y~%.2f (stupid printf rounding)\n", \$x, \$y; \$x = consistentlyRound( \$x ); \$y = consistentlyRound( \$y ); print "x~\$x y~\$y (consistent arithmetic rounding)\n"; __END__ x=0.015 y=0.015 x~0.01 y~0.01 (stupid printf rounding) x~0.02 y~0.01 (consistent arithmetic rounding)

It is just that your arithmetic adds more floating point operations that can change the inconsistency! I can find cases where your particular arithmetic happens to be more consistent than sprintf's. Above I show a case where sprintf() is more consistent.

Now go read the other replies and/or what they link to more carefully and learn why.

- tye

In reply to Re^2: Printf/Sprintf Behavior Change (stupid printf) by tye
in thread Printf/Sprintf Behavior Change by stingles

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.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, 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, 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: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and a soft breeze sighs...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2018-02-25 21:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When it is dark outside I am happiest to see ...

Results (315 votes). Check out past polls.

Notices?