0

Why show incorrect result with php function ?

This is my code. It's must to show 0

But when i test this code. It's show 99

Why ?????

<?PHP
$first = "8.12";
$second = "0.12";
$first = ($first)*(100);
$second = ($second)*(100);
$results = ($first)-($second);
echo ($results)%(100);
?>

1 Answers1

0

This seems to be a weird issue with floating point variables (double). Here's how you can fix it without worrying about casting variables:

$first = "8.12";
$second = "0.12";
$first = ($first)*(100);
$second = ($second)*(100);
$results = round(($first)-($second));
echo ($results)%(100);

Adding round to the results calculation (or, if you want, when multiplying $first and $second with 100) will solve the floating point error.

You can also specify the precision of round() with a second argument, such as

round(123.4567, 2); // 123.46
Jake Bathman
  • 1,268
  • 3
  • 18
  • 25