How do I convert a string to a number in PHP?
I want to convert these types of values,
Number(), but is there any similar method available in PHP?
Input Output '2' 2 '2.34' 2.34 '0.3454545' 0.3454545
You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, cast it:
$num = "3.14"; $int = (int)$num; $float = (float)$num;
Read more... Read less...
There are a few ways to do so:
To avoid problems try
intval($var). Some examples:
<?php echo intval(42); // 42 echo intval(4.2); // 4 echo intval('42'); // 42 echo intval('+42'); // 42 echo intval('-42'); // -42 echo intval(042); // 34 (octal as starts with zero) echo intval('042'); // 42 echo intval(1e10); // 1410065408 echo intval('1e10'); // 1 echo intval(0x1A); // 26 (hex as starts with 0x) echo intval(42000000); // 42000000 echo intval(420000000000000000000); // 0 echo intval('420000000000000000000'); // 2147483647 echo intval(42, 8); // 42 echo intval('42', 8); // 34 echo intval(array()); // 0 echo intval(array('foo', 'bar')); // 1 ?>
In whatever (loosely-typed) language you can always cast a string to a number by adding a zero to it.
However, there is very little sense in this as PHP will do it automatically at the time of using this variable, and it will be cast to a string anyway at the time of output.
Note that you may wish to keep dotted numbers as strings, because after casting to float it may be changed unpredictably, due to float numbers' nature.
You can use:
Or you can use:
If you want get a float for
$value = '0.4', but int for
$value = '4', you can write:
$number = ($value == (int) $value) ? (int) $value : (float) $value;
It is little bit dirty, but it works.