THOMAS,ANN (HP-Singapore,ex1) wrote:
> Hi
>
> I was doing successive additions of amounts using the code below:
>
> $totalamount += $currentarray[5];
>
> This line of code was inside a loop which looped for about 4000 times
> and for certain amounts, the sum came out funny!
>
> eg: It added the amount 3458.11 to the total 739474.59 to give
> 742932.699999999( instead of the correct sum 742932.70).
>
> And then when the amount 22.17 was added to this 742932.699999999, the
> total became 742954.87!
>
> My code is not doing any formatting of the numbers; just the above line
> of code and then a print statement to write the totalamount. And if I
> try to add these 2 numbers in another perl program(without putting it
> inside the loop), it gives the correct sum. Can somebody explain what is
> going wrong?
That's just a floating point rounding error. You could stick a sprintf in
there if it bothers you.
$totalamount += sprintf "%.2f", $currentarray[5];
or maybe better:
$totalamount = sprintf "%.2f", $totalamount + $currentarray[5];
--
,-/- __ _ _ $Bill Luebkert ICQ=162126130
(_/ / ) // // DBE Collectibles Mailto:[EMAIL PROTECTED]
/ ) /--< o // // http://dbecoll.tripod.com/ (Free site for Perl)
-/-' /___/_<_</_</_ Castle of Medieval Myth & Magic http://www.todbe.com/
_______________________________________________
Perl-Unix-Users mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs