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.