Is there a way to typecast a variable to a number only? Something like $var=(int)$var;
, but not for integers? $var=is_numeric($var)?$var:NULL;
doesn't seem right. Would $var=1*$var;
be best? Thanks
Unlike javascript
there are two different numeric types in PHP: integer
and float
. Therefore there are two ways how to convert to number:
$var = (integer) $var
$var = (float) $var
Both can be expressed as a function as well:
$var = intval($var);
$var = floatval($var);
Seems that you are looking for (float)
or floatval()
as you are using floating point numbers.
Other than the above two solutions .. you can also try like
$var=$var+0; //adding a zero
but it won't make mush sense since every scripting language does the same (based on context). What I mean is .. the moment you try to do a mathematical operation it will be casted to number before performing the operation on it.
Hope it make some sense.