As previous posts have mentioned, floating point numbers are only stored in a limited precision. If your number can be written in a binary non-repeating decimal , your ok, but for repeating floating point numbers in binary way, some accuracy is lost. For example, 1/4th can be written as a binary non-repeating decimal, (1/4 = 0.01 binary), but 1/5th is repeating in binary form (1/5 = 0.00110011...) and will get truncated. This means that for a computer, 1/5 is not 0.2!

The important lesson is that you should never (I mean it!) compare floating point numbers for equality. By the way, this goes for most programming languages.

To solve your problem, write the numbers as a formatted string wide enough, and compare those. For example:

my $val1 = 17554.61 - 2194.33; my $val2 = 19748.94; my $val1_str = sprintf("12.2f", $val1); my $val2_str = sprintf("12.2f", $val2); print ("equal\n") if ($val1_str eq $val2_str);

In reply to Re: perl subtraction by lyklev
in thread perl subtraction by jagdish.eashwar

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.