Question

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

Was it helpful?

Solution

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;

OTHER TIPS

(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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top