2

I have written the following PHP snippet to show some weird PHP behavior.

<?php
$amount = "9.95";
var_dump($amount); // string(4) "9.95" 
echo '<br />';

settype($amount, "float");
var_dump($amount); // float(9.95)
echo '<br />';

$amount = $amount * 100;
var_dump($amount); // float(995)
echo '<br />';

settype($amount, "int");
var_dump($amount); // int(994)
?>

I expected the last output to be 995, but instead the result is 994. Why is this happening? Online snippet: http://codepad.org/tpnxwm0W

user2191227
  • 392
  • 3
  • 15
  • Floats are not a precise data type. You can read more about it in [PHP's manual](http://php.net/manual/en/language.types.float.php) and on [Why don't my numbers add up?](http://floating-point-gui.de/). – M. Eriksson Nov 29 '17 at 16:12
  • 1
    This is not php specific. This problem happens on most (or maybe all) programming languages. It's because of the base 2 (binary). – Andreas Nov 29 '17 at 16:15
  • Here's a jsfiddle with the same issue in js: https://jsfiddle.net/cmkzr22w/. If you need precise numbers, don't use floats. – M. Eriksson Nov 29 '17 at 16:26

0 Answers0