Search code examples
phpcalculationfloor

PHP - Why floor() give me another result of sams calculation


 for($i=0;$i<=15120;$i+=504){
      echo ($i/60/8.4) . " - " .floor($i/60/8.4)."<br>";
 }

Result (i make ** at problem) :

0 - 0

1 - 1

2 - 2

3 - 3

4 - 4

5 - 5

6 - 6

7 - 6

8 - 8

9 - 8

10 - 10

11 - 11

12 - 12

13 - 13

14 - 13

15 - 15

16 - 16

17 - 17

18 - 17

etc...

At start i think i apply "Floo" at all calculation but (for line "7-6") also $i = 3528 :

3528 / 60 = 58,8 == Floor ==> 58 / 8 = 7.25 

floor of 7.25 =/= 6


Solution

  • it because of PHPs floating point precision

    so your 8th calculation for example will not return 7, but something like 6.9999999999999999999999999999

    as this is a double, it will be rounded to 7 on output, try this out:

    $x = 6.9999999999999999999999999999999999999999999999999999999;
    echo $x;
    

    when you use floor() it will (correctly) round it down to 6