Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

In the following example, $customers{$custid}{total} = 194.55 and $total_payments = 194.55.

$customers{$custid}{total} -= $total_payments;

The above code gives me a result of: 2.8421709430404e-14 (this is the problem)

If I replace $total_payments with 194.55 ($customers{$custid}{total} -= 194.55;), it works properly and gives me a result of 0. Do I need to do something with $total_payments before subtracting it? Thanks in advance for your help.

Replies are listed 'Best First'.
Re: subtraction not working right
by GrandFather (Saint) on Jan 26, 2006 at 09:02 UTC

    This is classic floating point rounding/truncation symptom. The two values are calculated in different ways so end up being rounded/truncated differently and become very slightly different values. You could fix it by storing cents rather than dollars (integers rather than floats).


    DWIM is Perl's answer to Gödel
Re: subtraction not working right
by saintmike (Vicar) on Jan 26, 2006 at 08:55 UTC
Re: subtraction not working right
by strat (Canon) on Jan 26, 2006 at 08:58 UTC

    if not necessary, don't calculate with numbers with after comma positions because in many cases there are storing/rounding problems.

    Better calculate in cent, not in dollars, and so you just need to store and caculate with plain integers

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"

Re: subtraction not working right
by tbone1 (Monsignor) on Jan 26, 2006 at 12:52 UTC
    This is why us oldtimers have always stored prices in cents, not dollars. Accountants don't like rounding errors, and the bean counters rule the world.

    --
    tbone1, YAPS (Yet Another Perl Schlub)
    And remember, if he succeeds, so what.
    - Chick McGee

Re: subtraction not working right
by chargrill (Parson) on Jan 26, 2006 at 08:53 UTC
    Hmm...

    Are you sure your values are as you say they are before the -= op?

    $ cat tam #!/usr/bin/perl $cid = 1; $c{$cid}{total} = 194.55; $tp = 194.55; $c{$cid}{total} -= $tp; print "new val: $c{$cid}{total}\n"; $ perl tam new val: 0
    $/ = q#(\w)# ; sub sig { print scalar reverse join ' ', @_ } + sig map { s$\$/\$/$\$2\$1$g && $_ } split( ' ', ",erckha rlPe erthnoa stJu +" );
Re: subtraction not working right
by Anonymous Monk on Jan 26, 2006 at 09:17 UTC
    Thanks everyone. I did a sprintf( "%6.2f", $value); on everything before the subtraction and it's giving me the correct results.