1

I have been getting information from the database which adds the cost of each item in a table.

Every is working 100% apart from when the cost is equal to a curtain sum it does not become equal, it is always greater.

For example if 30.02 == 30.02 it should become true, but its saying it is greater than.

Basically I have a foreach loop which is getting the cost of each invoice from an array which goes like this:

$i_array = array('2','3','4','5');
$i_total = 0;
$a_total = 0;
foreach($i_array as $i){ $i_total += floatval($i); }

Then I have a little bit of code which checks all invoices and if there are any it then adds them like this:

$query = $pdo->prepare("SELECT cost FROM tablename WHERE id=id");
$query->execute(array(':id' => $_GET['id']));
while($fetch = $query->fetch()){
$a_total += floatval($fetch['cost']);
}

From there I do a simple if statement:

if($i_total > $a_total){ echo 'Too Much'; }

Now the problem is if i_total is lets say 30.02 and lets say the a_total is also 30.02 then it should be equal and it should not echo Too Much but its still echos Too Much.

If the i_total is lower or greater it is fine, just when its equal.

Anyone could shed some light on this it would be greatful :)

Robert
  • 907
  • 4
  • 13
  • 32
  • Float values are never equal. – u_mulder Feb 03 '17 at 14:29
  • 3
    Check out the answer here http://stackoverflow.com/questions/3148937/compare-floats-in-php –  Feb 03 '17 at 14:29
  • And a manual http://php.net/manual/en/language.types.float.php#language.types.float.comparison – u_mulder Feb 03 '17 at 14:30
  • Sorry guys I did not know it was a duplicate because I was searching for an hour and did not find anything on here... I simply did not search compare floats because I did not know about not being able to compare in a simple if statement for a float – Robert Feb 03 '17 at 14:37
  • @NikolayGanovski thank you so much, if you could put that as an answer I would gladly accept it to give you some XP on here – Robert Feb 03 '17 at 14:39

1 Answers1

1

You could try with number_format(). Then you are comparing string values instead of float.

Bojan Radaković
  • 430
  • 3
  • 12