how to compare 2 numbers?

Discussion in 'PHP' started by aayybb, Feb 4, 2009.

  1. #1
    Hi,

    The server I use is running PHP 4 and PHP 5. I have run the following codes and don't understand why none of the if statement return true since the results should be 58 no matter what. What is the best way to compare 2 numbers regardless how many decimal points they have.

    <?php
    $a= .58;
    $b= 100;
    $c = 58.0000;

    if (($a * $b) == $c)
    {
    print 'a*b == c';
    print '$a'.$a.' '; print '$b'.$b.' '; print '$c'.$c.' ';
    }
    else
    {
    print 'duh1? if (($a * $b) == $c)<br />';
    print '$a '.$a;
    print '<br />';
    print '$b '.$b;
    print '<br />';
    print '$c '.$c;
    print '<br />';
    print '<br />';
    }

    if (($a * $b) == (int)$c)
    print 'a*b == c';
    else{
    print 'duh2? if (($a * $b) == (int)$c)';
    print '<br />';
    print '($a * $b) '.$a * $b;print '<br />';
    print '(int)$c '.(int)$c;print '<br />';
    print '<br />';
    }

    if (((int)($a * $b)) == (int)$c)
    {print 'a*b == c';
    print (int)($a * $b);
    }
    else
    {
    print 'duh3? if (((int)($a * $b)) == (int)$c)';
    print '<br />';
    print '(int)($a * $b) '.(int)($a * $b); // this one return 57 instead the expecting 58
    print '<br />';
    print '(int)$c '.(int)$c;print '<br />';
    print '<br />';
    }
    if (($a * $b) == ($c * 1))
    print 'a*b == c';
    else
    {
    print 'duh4? if (($a * $b) == ($c * 1))';print '<br />';
    print '($a * $b) '.($a * $b);print '<br />';
    print '($c * 1) '.($c * 1);print '<br />';
    }

    ?>
     
    aayybb, Feb 4, 2009 IP
  2. steelaz

    steelaz Peon

    Messages:
    47
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You should never compare floating point numbers, it says so right in the PHP manual. You may get your desired result like this, but it's still not recommended:

    
    $y = intval(round(($a * $b), 2));
    $c = intval(round($c, 2));
    
    if ($y == $c) { }
    
    PHP:
     
    steelaz, Feb 4, 2009 IP
  3. aayybb

    aayybb Peon

    Messages:
    128
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you very much, steelaz.

    You gave me an idea. I will use floatval() to do the comparison. This will work for me.

    Thanks again.
     
    aayybb, Feb 4, 2009 IP
  4. articlesdirectory

    articlesdirectory Greenhorn

    Messages:
    57
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    18
    #4
    I tried the above code but i have some questions related to it.

    1. Why PHP is so general in numbers syste although C or C++ is not. We must declare int, float or any other data type ..
    2. How can i control compiler of the wamp ..??


    Regards
     
    articlesdirectory, Jul 30, 2009 IP