Mike Fonder
Mike Fonder

Reputation: 61

PHP Type Casting

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?

Upvotes: 0

Views: 3770

Answers (3)

Ankur Kumar Singh
Ankur Kumar Singh

Reputation: 619

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.

Upvotes: 0

Marc B
Marc B

Reputation: 360602

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)

Upvotes: 0

Drumbeg
Drumbeg

Reputation: 1934

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.

Upvotes: 3

Related Questions