0

Please can anyone explain what's happening here?

$num1 = 37.29;
$num2 = 29.83;
$exp1 = round(($num1-$num2)*100); // 746.0 => OK
$exp2 = (($num1-$num2)*100); // 746.0 => OK
$exp1 == $exp2; // false => expected TRUE
746.0 == 746.0; // true => OK

OK, perhaps it is the broken floating point math, but I need the most suitable function anyway.

I'am trying to round_up prices in this way:

1.2345 Eur = 1.24 Eur

1.2567 Eur = 1.26 Eur

but this behavior does me serious headache. Or is there any better way to round up the values? I need this function:

function round_up(float $price, int $decimalPlaces = 2): float {...}

EDIT: I also try the ceiling() function (https://www.php.net/manual/en/function.ceil.php#85430):

$num1 = 37.29;
$num2 = 29.83;
ceiling(7.46, 0.01); // 7.46 => OK
ceiling($num1-$num2, 0.01); // 7.47 => wrong!!!

EDIT2: This works but it's not very intuitive and do the math this way in the whole application would be bad:

ceiling(ceiling($num1, 0.01) - ceiling($num2, 0.01), 0.01); // 7.46 => OK

Thanks

Peter
  • 93
  • 2
  • 6
  • You *can't* expect to ever get exactly "7.46" out of any operation involving floats. Float values may not be able to even represent the value you're expecting exactly. If you require this kind of precision, do not use floats! Use strings and https://www.php.net/manual/en/ref.bc.php, or work with your monetary values in cents as integers and divide them by 100 and format them only for display. – deceze Sep 22 '20 at 07:49
  • 2
    Working with currency is a minefield that's deceptively hard, and these sorts of rounding issues are just the start of it. There are dedicated implementations of the Money pattern in PHP and you should switch to one of them, rather than treating money as just numbers. – Matthew Daly Sep 22 '20 at 07:59

0 Answers0