In php arithmetic operation
<?php
$lower = floor(63.1);
$value = 63.1;
echo $value - $lower;die; ?>
i get the answer as 0.1, but when i do the same for 64.1-64 i get the result as 0.099999999999994 Why is it so?
In php arithmetic operation
<?php
$lower = floor(63.1);
$value = 63.1;
echo $value - $lower;die; ?>
i get the answer as 0.1, but when i do the same for 64.1-64 i get the result as 0.099999999999994 Why is it so?
It's a problem that many languages, not just PHP have, when running on hardware (like most hardware) that supports floating point in binary or base-2 (base-16 as a shorthand) but not in base-10 that we humans use (and often assume is the only way to represent numbers).
0.1 to us humans is a base-10 notation which means 1 x 10**-1. This cannot be represented accurately in base-16. Closest is 9 x 16**-2 + 9 x 16**-3 ...
Base-10 has this problem in reverse. Base-10 represents the fraction 1/3 as 0.333333... But if we were using base-3, it would be a succinct 0.1 = 1 x 3**-1.
In PHP, if you need better base-10 precision, use the BC Math functions.
(Note some hardware can represent numbers in base-10. Mainframes, for example, for 50+ years have "packed decimal" and the corresponding native opcodes to process this. Not surprising, as they were built as business machines for accurately handling base-10 things like money!).