0

PHP is giving an unexpected result for this multiplication that is required by Stripe (value in pennies) when creating a payment intent.

<?php
$val = 580.80;
$res = (int)($val * 100);
echo $res; //Outputs 50879
?>

I would expect the output of this to be 58080, however it is 58079.

Removing the integer cast outputs 58080 which is the expected result, for example:

<?php
$val = 580.80;
$res = ($val * 100);
echo $res; //Outputs 50880
?>

Does anyone have any reasoning of this strange behaviour?

Here are some example outputs, ran through the initial function example with the integer cast:

Val: 580.80, Result: 58079, FAIL
Val: 580.81, Result: 58080, FAIL
Val: 580.82, Result: 58082, SUCCESS
Val: 580.90, Result: 58090, SUCCESS
Val: 480.90, Result: 48090, SUCCESS
Val: 480.80, Result: 48080, SUCCESS
Val: 480.80, Result: 48080, SUCCESS
Val: 1580.80, Result: 158080, SUCCESS

This is obviously something to do with casting the result to an integer, but why does it only happen on specific values as seen above?

Ryan
  • 3,552
  • 1
  • 22
  • 39
  • If you read the answer, it does actually tell you why. Don't forget to click on the links in the answer as well, since that will give you even more info. Here's even more info: https://floating-point-gui.de/basic/ – M. Eriksson Feb 11 '20 at 15:31
  • Short answer, `(int)` truncates, so see `echo serialize($res); echo (int)$res;` – AbraCadaver Feb 11 '20 at 15:38

0 Answers0