0

I have some code, which checks if a paid amount on our account is the same as it should be based on the bought items.

Here is some "Pseudocode":

$income = $this->getIncome();
$invoiceSum = $order->getInvoiceSum();
if($income != $invoiceSum ) echo "Error";

which gives me the "Error" output, even if the values are the same.

The value of $income is from a Rest API (JSON), where the $invoiceSum is calculated by my code based on the net values all ordered products multiplied by the tax rate.

If i do:

echo $income . " " . gettype($income) . "<br>";
echo $invoiceSum . " " . gettype($invoiceSum) . "<br>";

I get:

19.71 double
19.71 double

Which is what I expect.

So I tried to calculate as intvalues (=Cent instead of €). And now the weird part starts:

echo intval($income * 100);
echo intval($invoiceSum * 100);

and i get:

1970
1971

Hm? How to fix this, so i get the correct value?

bernhardh
  • 3,137
  • 10
  • 42
  • 77
  • It is highlighted in red in the documentation of the [`float`](http://php.net/manual/en/language.types.float.php#language.types.float.comparison) type. – axiac Oct 16 '17 at 09:00
  • And btw, [`intval()`](http://php.net/manual/en/function.intval.php) doesn't round. It truncates. And it turns your lack of knowledge about how the floating point numbers work into a trouble. – axiac Oct 16 '17 at 09:02
  • @bernhardh not able to replicate error – shashi Oct 16 '17 at 09:06
  • You should read how floating-point numbers work: https://en.wikipedia.org/wiki/Floating-point_arithmetic – ventaquil Oct 16 '17 at 09:10
  • @axiac: If I would know it, I wouldn't ask it. And "a lack of knowledge" is the reason why stackoverflow exists. So thank you for your hint to solve MY problem, but you should think about the way you present your knowledge. – bernhardh Oct 16 '17 at 09:15
  • @bernhardh you are a member of [so] for enough time to know that one of the rules of [so] is to search for the problem before asking a question. Maybe it was already answered and by not asking it again you save your time as well as others. And your question was asked and answered many times on [so]: https://stackoverflow.com/q/10334688/4265352, https://stackoverflow.com/q/17333/4265352, https://stackoverflow.com/questions/14587290/can-i-rely-on-php-php-ini-precision-workaround-for-floating-point-issue to mention just a few. – axiac Oct 16 '17 at 09:25

1 Answers1

0

From here, to get the output you want, you might have to do this

var_dump( (int)($income * 100) );
var_dump( (int)($invoiceSum * 100) );
kellymandem
  • 1,709
  • 3
  • 17
  • 27