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.
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
<?php
$num = "1000.314" ;
echo number_format( $num ), "\n" ;
echo number_format( $num , 2);
?>
|
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
<?php
$num = "1000.314" ;
echo (int) $num , "\n" ;
echo (float) $num , "\n" ;
echo (float) $num ;
?>
|
Output
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.
PHP
<?php
$num = "1000.314" ;
echo intval ( $num ), "\n" ;
echo floatval ( $num );
?>
|
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
<?php
$num = "1000.314" ;
echo $num + 0, "\n" ;
echo $num + 0.0, "\n" ;
echo $num + 0.1;
?>
|
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
04 Dec, 2023
Like Article
Save Article