On May 27, Andrew Gaffney said:

>I am writing a program to parse a CSV file downloaded from my bank. I have it
>keep a running balance, but I'm getting a weird total. Apparently, -457.16 +
>460.93 = 3.76999999999998. But when 20 is subtracted from that, I get -16.23.
>There are no weird numbers like that in my input data. All numbers have no more
>than 2 numbers after the decimal point. Here is my code:

I suggest 'perldoc -q numbers'

Found in /usr/local/lib/perl5/5.8.4/pod/perlfaq4.pod
  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 binary.
    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 lan-
    guages, not just Perl.

    perlnumber show the gory details of number representations and conver-
    sions.

    To limit the number of decimal places in your numbers, you can use the
    printf or sprintf function.  See the "Floating Point Arithmetic" for
    more details.

      printf "%.2f", 10/3;

      my $number = sprintf "%.2f", 10/3;

I think the 'perlnumber' documentation is new to Perl 5.8, but it might
exist back to 5.6.

Anyway, just use sprintf() or printf() when you need to be sure your
precision is what you expect it to be.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
CPAN ID: PINYAN    [Need a programmer?  If you like my work, let me know.]
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to