PHP convert string to number


PHP convert string to number : We sometimes need to convert the string to integer. There are many ways to convert string to number. Here in this tutorial we are going to explain how you can convert a string to number forcefully using different methods. We will also explain how to convert string to float etc.


PHP convert string to number – Interger Example

If you have string like – “33.3” and you want to convert it to integer use the type cast as below –

PHP convert string to number – integer example:

$number = "33.3";
$int = (int)$number;

In this example $number variable contains the string with “33.3”. Double quotes makes it string so we have used type cast int to convert it to integer.


More About String to Number

Let us learn more about conversion –


PHP convert string to Integer : inval() function Example-

You can also convert string to integer using the function intval. Here is an example of intval-

PHP convert string to integer example:

$number = "33.3";
$int = intval($number);

The above function takes the string and returns the integer.

Now let us have some example about the float conversion.

PHP convert string to float Method 1

You can also convert string to float using the type cast (double) as below –

PHP convert string to float example:

$number = "33.3";
$int = (double)$number; // will give 33.3
or 
$int = (float)$number; // will give 33.3

The double type cast will convert the number in float.

PHP convert string to float Method 2 : floatval() Function Example

You can also convert string to float using the floatval() function as below –

PHP convert string to float example:

$number = "33.3";
$int = floatval($number); // will give 33.3

The floatval() takes string and converts it to the float as above.


Advertisements

Add Comment

📖 Read More