![]() |
VOOZH | about |
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:
Table of Content
We will explore all of the mentioned approaches with the help of suitable examples.
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.
1,000 1,000.31
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.
1000 1000.314 1000.314
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.
1000 1000.314
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.
1000.314 1000.314 1000.414
The filter_var() function in PHP can be used to convert a string to a number by using the FILTER_SANITIZE_NUMBER_FLOAT or FILTER_SANITIZE_NUMBER_INT filter. This function is versatile and can handle various types of sanitization and validation.
Example: This example illustrates converting a string into a number in PHP using the filter_var() function.
123.4512345
The settype() function is used to convert a variable to a specified type. This function can change the type of a variable to integer or float, among other types. It is another effective way to convert a string to a number in PHP.
Example: This example illustrates converting a string into a number in PHP using the settype() function.
1000 1000.314
The sscanf function in PHP can be used to parse input from a string according to a specified format. This function can be leveraged to convert a string into a number, such as an integer or a float.
12345.678998765
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.