skip to Main Content

Can someone please help me figure out why this most basic of code isn’t working in PHP? Have used PHP for years and have never seen this… It is consistent on every version of php as I tested it with the sandbox.onlinephpfunctions.com website, see link below the snippet of code.

All I want to do is to compare one number to another, but when the numbers contain floats things get weird.

<?php

$lside = 490.84;
$rside = 237.80 + 222.00 + 31.04;

if( $lside == $rside ){
   echo "they are equaln";
} else {
   echo "not equaln";
   echo "rside: [$rside]n";
   echo "lside: [$lside]n";
}

http://sandbox.onlinephpfunctions.com/code/6dee3a97f68a11e67fbaa8e5c157b827ecd47740

Help and thanks!

edit: here is how I ended up fixing this from the answers I received and looking into this further:

<?php

$lside = 490.84;
$rside = 237.80 + 222.00 + 31.04;

if( (string)$lside == (string)$rside ){
   echo "they are equaln";
} else {
   echo "not equaln";
   echo "rside: [$rside]n";
   echo "lside: [$lside]n";
}

So to compare two numbers in PHP, one safe way is to force them to be strings… go figure.

And I some additional testing to make sure this is true and always seems to work. All of these return “good”:

if( "1" == "1" ) echo "1 - goodn";
if( "1.0" == "1" ) echo "2 - goodn";
if( "1" == "1.0" ) echo "3 - goodn";
if( "1.0" == "1.0" ) echo "4 - goodn";
if( "1.0" == "1.00000000" ) echo "5 - goodn";
if( "1.000000000000000" == "1.00000000" ) echo "6 - goodn";
if( "2" == (string)(.5+.5+1) ) echo "7 - goodn";
if( "2.000000000000000" == (string)(1+1) ) echo "8 - goodn";
if( "2.000000000000000" == (string)(1.0+1) ) echo "9 - goodn";
if( "2.4" == (string)(1.4+1) ) echo "10 - goodn";
if( "2.40000" == (string)(1.4+1) ) echo "11 - goodn";
if( "2.000000000000000" == (string)(.5+.5+1) ) echo "12 - goodn";
if( "1.5" == (string)(.5+.5+.5) ) echo "13 - goodn";
if( "1.500000000000000" == (string)(.5+.5+.5) ) echo "14 - goodn";

2

Answers


  1. You can try this :

    if( bccomp($lside, $rside, 2) == 0 ){
       echo "they are equaln";
    } else {
       echo "not equaln";
       echo "rside: [$rside]n";
       echo "lside: [$lside]n";
    }
    

    Because there’s a complex thing when you compare float, you can read more here, and for the bccomp function you can read more here

    Login or Signup to reply.
  2. Try This

    $lside = 490.84;
    $rside = 237.80 + 31.04 + 222;
    $newRside = number_format($rside,2);
    
    if( $lside == $newRside ){
       echo "they are equaln";
    } else {
       echo "not equaln";
       echo "rside: [$rside]n";
       echo "lside: [$lside]n";
    }
    

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search