0

enter image description here

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?

2
  • 2
    Possible duplicate of Is floating point math broken? Commented Jul 6, 2019 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 directive determines. Commented Jul 7, 2019 at 12:05

1 Answer 1

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 to int, which truncates, producing 19.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.