Convert a string to a number in PHP

Convert a string to a number in PHP is quite simple, let me show you the problem and the solution for it.

 

number

Here is what we need to do

Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545

Now, let ‘s do the magic

$num = "3.14";
$int = (int)$num;
$float = (float)$num;

For more detail you can do like this

1. Cast the strings to numeric primitive data types:

$num = (int) "10";
$num = (double) "10.12"; // same as (float) "10.12";

2. Perform math operations on the strings:

$num = "10" + 1;
$num = floor("10.1");

3. Use intval() or floatval():

$num = intval("10");
$num = floatval("10.1");

I think they are good enough for you to convert string to any number type.

CDN by MaxCDN