0

So I was asked as part of my homework to cast a floating point number to integer in PHP. Problem is that no such cast is possible according to php.net and I myself cannot find the notion behind the question.

Given the following:

$float = 1.92;
$float += 2;

It'll just substitute them resulting in 3.92 as an output.


As far as I could see the possible (or rather allowed) casts are as follows:

The casts allowed are:

(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5)

Is it some sort of trick that they have presented us with or the task is invalid?

Mike Fonder
  • 61
  • 2
  • 6

3 Answers3

3

Was the task to round the float to the nearest whole number? In which case:

$float = 1.92;
$float += 2;

echo round($float);

outputs 4. Or a straight cast:

$float = 1.92;
$float += 2;

echo (int) $float;

outputs 3.

Drumbeg
  • 1,914
  • 1
  • 15
  • 22
  • I suppose the second example should be valid and accepted as a solution. I'll proceed with it. Thanks for your time :) – Mike Fonder Jun 11 '14 at 21:23
0

What makes you think you can't cast float to int?

php > $float = 1.92;
php > var_dump($float);
float(1.92)
php > $int = 2 + (int)$float;
php > var_dump($int);
int(3)
php > $int2 = (int)(2 + $float);
php > var_dump($int2);
int(3)
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

You can always convert the float number to string like for your code

$float = 1.92;
$float +=2;
$int = (int)$float;
echo $int;

PHP always supports float to integer type casting.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343