0

i am making a code to divide money in euros and cents. When i put 7.35, i get back 1 x 5 euro - 1 x 2 euro - 1 x 20 cent - 1 x 10 cent and 2 x 2 cent. This is where it's goes wrong, i want to have 1 x 5 cent. Funny part is when i put 7.65 i get it with the 5 cent. I think i am doing something wrong with the rounding, can someone help me?

$r = floatval($argv[1]);
define('MONEY_UNITS', array(50, 20, 10, 5, 2, 1));
foreach (MONEY_UNITS as $money) {
    if ($r >= $money) {
        $a = floor($r / $money);
        $r = fmod($r, $money);
        echo $a . " x " . $money . "euro";
    }
}
$r = $r * 100;
foreach (MONEY_UNITS as $cents) {
    if ($r >= 5) {
        $ac = floor($r / $cents);
        $r = fmod($r, $cents);
        $cent = round($cents);
    if ($ac >= 1) {
        echo $ac . " x " . $cent . " cent";
    }
    }
}

p.s i must use floor, fmod.

Kenan
  • 9
  • 2
  • 1
    Don't use floating point for money. Some of the values can't be represented accurately, and the error can go either way. – Barmar Jan 14 '22 at 20:22
  • 1
    Do everything using integers, where the units are the cents instead of euros. – Barmar Jan 14 '22 at 20:23
  • +1 for this, you should not add decimals (floating points) until you display the final result on the page, so treat as an integer all the way. This will eliminate rounding errors and is the general way eCommerce sites operate. – John Lewis Jan 14 '22 at 20:27

0 Answers0