skip to Main Content

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

2

Answers


  1. Floor rounds down to the base of it, ceil would raise the value as per the names of the functions. round determines either-or (iirc)

    so in your example, 99.9 floored would be 99 and ceil would be 100

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search