If you do var_dump((799-639.20)*100/799); it will gives float(20) as result. If I int conversion, I get 19. Can anybody explain on what might be happening here?
Asked
Active
Viewed 108 times
0
-
2Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Dharman Jul 06 '19 at 21:49
-
Please note that floating point numbers are binary data structures. When you `var_dump()` them you get a transparent lossy conversion to base 10 with as many digits as the [precision](https://www.php.net/manual/en/ini.core.php#ini.precision) directive determines. – Álvaro González Jul 07 '19 at 12:05
1 Answers
4
I cannot speak to the official semantics of PHP, but, quite likely:
- The calculation
(799-639.20)*100/799)
yields 19.999999999999996447286321199499070644378662109375, due to use of IEEE-754 basic 64-bit binary floating-point. - The output shown with
var_dump
does not show the full value; it rounds to a limited number of digits and shows “20”. For example, it may, in effect, format the number internally using 16 significant digits, which produces “20.00000000000000”, and then remove the trailing insignificant zeros and the trailing “.”, producing “20”. - The calculation
(int)(799-639.20)*100/799)
first produces 19.999999999999996447286321199499070644378662109375 as above and then converts it toint
, which truncates, producing 19.

Eric Postpischil
- 195,579
- 13
- 168
- 312