How to convert a String into Number in PHP ?

Strings in PHP can be converted to numbers (float/ int/ double) very easily. In most use cases, it won’t be required since PHP does implicit type conversion. This article covers all the different approaches for converting a string into a number in PHP, along with their basic illustrations.

There are many techniques to convert strings into numbers in PHP, some of them are described below:

We will explore all of the mentioned approaches with the help of suitable examples.

Using the number_format() Function

The number_format() function is an inbuilt function in PHP that is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure.

Example: This example illustrates the transformation of the string into a number in PHP & formats the number with a specific group pattern.

PHP

 ``

Output
```1,000
1,000.31
```

Using Type Casting

Type Casting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.

Example: This example illustrates converting a string into a number in PHP using Type Casting.

PHP

 ``

Output
```1000
1000.314
1000.314
```

Using the intval() and the floatval() Functions

The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.

Example: This example illustrates converting a string into a number in PHP using the intval() and the floatval() Functions.

PHP

 ``

Output
```1000
1000.314
```

Using Mathematical Operations

In this approach, we will be adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 to the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.

Example: This example illustrates converting a string into a number in PHP using Mathematical Operations.

PHP

 ``

Output
```1000.314
1000.314
1000.414
```

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

Previous
Next