Search code examples
phpcastingroundingphp-7.0

PHP 7.0 - rounding and/or casting float to int gives incorrect values


Consider dockerized Laravel (5.7) app running on nginx/php 7.0.33.

I'm experiencing weird rounding (?) error:

enter image description here

Can anyone explain me how floor($x) is 7256 instead of 7257?

Bonus:

enter image description here

Bonus 2: the same test in PHP 7.4 / 8 gives good results:

enter image description here


Solution

  • The best answer you'll find to your question is that computers don't handle floats all that well. Internally, the number 72.57 is actually figured to 72.569999999999999999999, which in most cases will calculate okay, but will cause you to run into exactly what you ran into, where if you multiply by 100 (7256.999999999999) then use FLOOR, you get 7256.

    There are entire articles on the problems computers have with handling floats, but the best solution when accuracy is important is to avoid the use of numbers to the right of the decimal point, where possible.

    This article talks about the issue in Python, but it applies to all languages: https://www.geeksforgeeks.org/floating-point-error-in-python/#:~:text=It's%20a%20problem%20caused%20when,leads%20to%20small%20roundoff%20errors.