Sure, but the point is that altho you see a number ending with ".33333" printed out, it may not have that exact value in memory, and if further calculations are performed, that could become apparent. Similarly, of course, decimal numbers cannot truly represent the fraction 1/3. The "galactic credits" example is a bit disingenuous -- when was the last time you wrote a check for $833.3333 to pay your mortgage? Again, money has a fixed precision of two decimal places and needs to be kept there. If rounding is an issue, use tenths of a cent as an integer unit and write a rounding function. This could be as simple as >=/< 5, since integers are round down (so what would have been 4.9999999 tenths of a cent will be 4, anything more will be five).

If you think it is more appropriate to round up (the bank wants at least what it is owned, ie, $8.34) you should still limit the precision with integers, otherwise you will end up with numbers like 1000.00000001 due to the floating point issues that motivated the original post, and if those are rounded up and collated you could be looking at whole dollars of error.


In reply to Re^5: Numeric Comparisons Randomly Giving the Wrong Result by halfcountplus
in thread Numeric Comparisons Randomly Giving the Wrong Result by Likeless

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.