Hi Andrew. Andrew Gaffney wrote: > > 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: > > #!/usr/bin/perl > > do './money.pl'; > # use strict and warnings is defined in money.pl
'strict' and 'warnings' are lexically scoped so they won't be effective outside money.pl and you need them in this file as well. > my $balance = 0; > > print $cgi->header; > print "<html><body>\n"; > print "<table>\n<tr><td width=100>Date</td><td width=60>Type</td><td > width=350>Description</td><td width=80>Withdrawl<td width=80>Deposit</td$ > my $csvdata = parse_csv("/tmp/usbank.csv"); > foreach(@{$csvdata}) { > print "<tr><td>$_->{date}</td><td>$_->{type}</td><td>$_->{descr}</td>"; > if($_->{amount} > 0) { > print "<td><br></td><td>$_->{amount}</td>"; > } else { > print "<td>$_->{amount}</td><td><br></td>"; > } > $balance += $_->{amount}; > print "<td>$balance</td></tr>\n"; This is a very common problem. Floating point numbers can't usually be held to a precision of 15 significant figures so Perl often prints a recurring decimal for the results of arithmetic. The best way around this for financial applications is to work in integral numbers of pennies (cents) and divide them down for the display. In this case you should be OK rounding to two decimal places with $balance += $_->{amount}; $balance = sprintf '%.2f', $balance; print "<td>$balance</td></tr>\n"; > } > print "</body></html>"; > > money.pl is an include file that contains the parse_csv() function which pulls > apart each line of the downloaded CSV and pushes it into an array as an > anonymous hash. HTH, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>