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

I came across a very odd situation and was hoping a fellow monk could clarify as why it happened/
I have a small snippet of code that compares numbers. It has worked fine for some time without problem until -2.97 came along.

I try to compare two numbers. The one way works as expected but the other does not.
my $batch_total = 297; my $batch_sign_indicator = '-'; my $close_response; $close_response->{batch_net_amount} = -2.97; #this code doesn't work. it returns false my $test_batch_amount = ($batch_sign_indicator eq '-') ? ((0 - $batch_ +total) / 100) : ($batch_total / 100); if($test_batch_amount == $close_response->{batch_net_amount}){ print "good!!! $test_batch_amount == $close_response->{batch_net_a +mount}"; } else{ print "no good $test_batch_amount == $close_response->{batch_net_a +mount}"; } ####THIS CODE DOES WORK AS EXPECTED AND RETURNS TRUE my $test_batch_amount = ($batch_sign_indicator eq '-') ? ((0 - $batch_ +total)) : ($batch_total); if($test_batch_amount == ($close_response->{batch_net_amount}*100)){ print "good!!! $test_batch_amount == $close_response->{batch_net_am +ount}"; } else{ print "no good $test_batch_amount == $close_response->{batch_net_am +ount}"; }
Why?? Thanks again.

Replies are listed 'Best First'.
Re: inequality of appearing same number
by davido (Cardinal) on Dec 01, 2004 at 18:09 UTC

    This has been coming up about once a week lately. See perlfaq4 under the topic, "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?".


    Dave

Re: inequality of appearing same number
by Roy Johnson (Monsignor) on Dec 01, 2004 at 18:15 UTC
Re: inequality of appearing same number
by dragonchild (Archbishop) on Dec 01, 2004 at 18:00 UTC
    You might be running into a floating point rounding error. In fact, that definitely sounds like the problem. Have you printed out the values to see what they really are?

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

Re: inequality of appearing same number
by Anonymous Monk on Dec 01, 2004 at 21:47 UTC
    Why 0 - $batch_total and not abs($batch_total)? (Not really sure if it would make a difference but it's worth the try...)
      there are some situations where the values could have the same abs but one was a - and the other was + originally and that would be a big error.
      Thanks for the help. I didn't realize this post was made so short ago.