为什么PHP认为3.57 + 0.01等于3.5799999999999996? [重复]

This question already has an answer here:

Somehow PHP thinks that 3.57 + 0.01 equals 3.5799999999999996 in my script.

I tested about 10 other sums like this (e.g. 10.51 + 0.01) and then PHP gave me the correct answer (10.52 in the latter case). So, weirdly enough it only seems to make this mistake with these specific floats.

Code: (simplified for readability)

$users = array();

$IDs = [1,2,3];

foreach($IDs as $ID)
{
  $user = (object) array();
  $user->ID = $ID;
  $users[] = $user;
}

$initialAmount = 3.57;

$chosenIDs = [1,3];

foreach ($users as $key => $value)
{
  $users[$key]->amount = $initialAmount;
  if(in_array($key, $chosenIDs))
  {
    //the following returns 3.5799999999999996
    $users[$key]->amount = $users[$key]->amount + 0.01;

    //even if I do it like the following, it returns the wrong answer
    $users[$key]->amount = 3.57 + 0.01; //according to PHP equals 3.5799999999999996

    //the following actually gives the correct answer though
    //$users[$key]->amount = ($users[$key]->amount * 100 + 1) / 100;
  }
}

Is this some weird error in my configuration, or what is going on here?

</div>

As others have mentioned, it's a problem with Floating Point Math, not php.

http://php.net/manual/en/language.types.float.php

You can avoid it by using the BC Math extension when working with numbers where Floating Point errors would be a problem. It supports arbitrary precision.

http://php.net/manual/en/ref.bc.php