0

Working example : http://ideone.com/Ond6PY

You have two variables namely $a = 5 and $b = 9

What are the major mathematical differences between these two statements?

floor(floor($a / $b) - .5); //output: -1

and

(int)((int)($a / $b) - .5); //output: 0

2 Answers2

3

Look to the rounding of parts of your expression.

The division of 5/9 is

$a / $b = 5 / 9 = 0.555555556

so see http://php.net/manual/en/function.floor.php

floor(1.5) = 1
floor(-1.5) = -2

then

floor(floor($a / $b) - .5) = floor(floor(0.555555556)) = floor(0 - .5) = floor(-.5) = -1

and the second case see http://www.php.net/intval

(int) 4.32 = 4

then

(int)((int)($a / $b) - .5) = (int)((int)(0.555555556) - .5) = (int)(0 - .5) = int(-0.5) = 0;
Martin Strejc
  • 4,307
  • 2
  • 23
  • 38
  • That's wrong. That's not intval, that's typecasting: look here!: http://php.net/manual/de/language.types.type-juggling.php – Sebi2020 Dec 21 '13 at 22:09
  • @Sebi2020 Right, even though that's not 'intval', the rounding algorithm is the same. I used the link because there is the explanation of rounding on php.net. If you've a better one edit the answer please. – Martin Strejc Dec 21 '13 at 22:17
  • Apparently I'm not. I got two downvotes for my answer. – Sebi2020 Dec 21 '13 at 22:23
-2

(int) is a typecast and you get an Integer e.g. 2, 3 , 5 etc. floor rounds down.

So with (int)((int) 5 / 9)-0.5) you get:

0 - 0 (0.56666666) = 0

(int) isn't a function! Look here: Type Casting - PHP DOC

Sebi2020
  • 1,966
  • 1
  • 23
  • 40