Chris wrote:
> 
> I am retrieving rows with a money datatype from a database. These are
> written to a file with 2 decimal places. I also keep a running total.
> My problem is the total does not equal to the sum of details.
> 
> I have tried using
> $amount = sprintf('%.2f', $amount);
> $total += $amount;
> 
> # do this after all tallying, just before writing to file
> $total = sprintf('%.2f', $total);
> 
> How do I tally money with perl?

Assuming that you are tallying dollars like $12,345.67, convert to cents
(an integer) by removing all punctuation and convert back to dollars to
print the final total.

$ perl -le'
@dollars = qw/ $12,345.67 $11,555.99 $9,765.35 $432 $876.4 /;
for ( @dollars ) {
    # add zeros for proper format
    $_ .= ".00" unless tr/.//;
    $_ .= "0"   unless /\.\d\d$/;
    # remove non-digits
    tr/0-9//cd;
    $total += $_;
    }
($total2 = $total) =~ s/(\d\d)$/.$1/;
printf "%.2f\n", $total / 100;
print $total2;
'
34975.41
34975.41



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to