1

Confused as to why the while loop is not being entered even though it appears conditions are met, for some values of payment this works fine. I have attempted to debug with echo, but this confirms that even with conditions met the while loop is not being entered.

<?php
function leastChange($price, $payment) {
    $coins = array();
    $change = $payment - $price;
    echo "$change <br>";

    while ($change >= 0.5) {
        $change -= 0.5;
        $coins[] = "50c";
    }
    while ($change >= 0.2) {
        $change -= 0.2;
        $coins[] = "20c";
    }

    while ($change >= 0.10) {
        $change -= 0.10;
        $coins[] = "10c";
    }

    while ($change >= 0.05) {
        $change -= 0.05;
        $coins[] = "5c";
    }

    echo "$change <br>";

    while ($change >= 0.02) {
        echo "entered 2c with $change<br>";
        $change -= 0.02;
        $coins[] = "2c";
    }

    while ($change >= 0.01) {
        echo "entered 1c with $change <br>";
        $change -= 0.01;
        $coins[] = "1c";
    }

    foreach ($coins as $item){
        echo $item. " ";
    }
       
}

leastChange(1.98, 8);
echo '<br>';
leastChange(1.98, 5);
?>

This is what is printed:

6.02.
0.02.
entered 1c with 0.02.
50c 50c 50c 50c 50c 50c 50c 50c 50c 50c 50c 50c 1c.

3.02.
0.02.
entered 2c with 0.02.
50c 50c 50c 50c 50c 50c 2c.

Jake Clifford
  • 25
  • 1
  • 7
  • If you echo $change in the loop again after you've subtracted 0.01 from it, you'll see the value is 0.0099999999999996 ...which explains the problem. Demo: http://sandbox.onlinephpfunctions.com/code/b4a7f64595c2cb41c631339cdabd13099150ad6e . Read https://stackoverflow.com/questions/588004/is-floating-point-math-broken . You may want to consider using some rounding. – ADyson Sep 23 '21 at 08:08
  • I haven't worked with PHP for a long time but my guess is that this is an issue from doing math operations with fractions and wrong rounding from PHP. This happens in other languages too. Try to do the extraction with something like round https://www.php.net/manual/en/function.round.php – George Pandurov Sep 23 '21 at 08:09
  • See also https://stackoverflow.com/questions/3819508/best-practice-for-working-with-currency-values-in-php – ADyson Sep 23 '21 at 08:09

0 Answers0