This is a FAQ. It would be good for you to review at least the table-of-contents at "perldoc perlfaq" from time to time, even if you don't read the actual FAQs.

The particular FAQ answers you'll need are:

Why am I getting long decimals (eg, 19.9499999999999) instead of the + numbers I should be getting (eg, 19.95)? Internally, your computer represents floating-point numbers in bin +ary. Digital (as in powers of two) computers cannot store all numbers exactly. Some real numbers lose precision in the process. This is +a problem with how computers store numbers and affects all computer languages, not just Perl. perlnumber show the gory details of number representations and conversions. To limit the number of decimal places in your numbers, you can use + the printf or sprintf function. See the "Floating Point Arithmetic" fo +r more details. printf "%.2f", 10/3; my $number = sprintf "%.2f", 10/3; Why is int() broken? Your int() is most probably working just fine. It's the numbers th +at aren't quite what you think. First, see the above item "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?". For example, this print int(0.6/0.2-2), "\n"; will in most computers print 0, not 1, because even such simple nu +mbers as 0.6 and 0.2 cannot be presented exactly by floating-point numbe +rs. What you think in the above as 'three' is really more like 2.9999999999999995559.

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.


In reply to Re: perl numeric expressions by merlyn
in thread perl numeric expressions by deckard

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.