perlfloating-pointfloating-point-comparison

In Perl, why does 100*18.35 not compare equal to 1835?


When I run the following Perl one-liner:

$ perl -e 'print "Oh no!\n" unless 1835 == 100*18.35'

I get

Oh no!

Why is that?


Solution

  • What you're missing is an old computer science problem - floating point conversion.

    You see, you cannot precisely represent '0.35' as a floating point number since it's a periodic number in binary.

    So if you add:

    my $new = $a->{a} - $b;
    print $new;
    

    You'll get:

    2.27373675443232e-013
    

    $a->{a} is very slightly more than $b and thus the test is correct.

    You can see this at work if you:

    my $new_val = 18.35 - 18;
    print $new_val;
    

    Whilst we're at it though - don't use $a or $b - they're reserved for sort. And single letter var names aren't good style anyway.

    Also my $a = {}; is redundant - there's no need to initialise an empty hash-reference like that.

    To do what you want, then you either need to compare 'like types' or cast explicitly to integer:

    $a->{a} = int(18.35 * 100);