- PHP: Convert String to Number
- Why Do We Need to Convert String to Integer in PHP?
- Using number_format() Function
- Using Type Casting settype()
- Using intval() and floatval() Function
- Performing Mathematical Operations on String Value
- By Adding Number «0» to String
- By Multiply Number «1» to String
- Conclusion:
- PHP- how to convert string to number?
- 8 Answers 8
- How to Convert a String to a Number in PHP
- Applying Type Casting
- Using intval() or floatval()
- Using number_format
PHP: Convert String to Number
While programming in PHP, there might be a situation where you have to convert a string into an integer. But we know that PHP does not need or support explicit type definition while declaring a variable. So you have to force a string to be converted into an integer.
We will look at the various ways by which a string can be converted into an integer in PHP in this article.
Why Do We Need to Convert String to Integer in PHP?
Sometimes you may need to convert a string into an integer, float or any other data type. This is because the data or values you are working on might be of a different data type. You might have an integer in a string format from the user. So you have to convert this string into a number for performing operations in the program.
Using number_format() Function
The number_format() function is an in-built method in PHP that is used for converting a string with grouped thousands. It takes 4 parameters:
string number_format ( $number, $decimals, $decimalpoint, $sep )
- $number — This is the number to be formatted. If you don’t set any other parameters, this number will be formatted without any decimals
- $decimals — This is the optional parameter that is used for specifying the decimals
- $decimalpoint — This specifies the string used for mentioning the decimal point
- $sep — This is a string specifying the thousands separator
If the method successfully converts the string, it returns the formatted number. On failure, it returns an E_WARNING error message.
number_format($string); // string into integer number_format($string,2); // string into float
Code Example:
Float Value: '.number_format($string,2); >else < echo 'Not a numaric value'; >?>
Integer Value: 25 Float Value: 25.00
Explanation:
In this program, an integer in the form of a string is assigned to a variable called $string. Then the is_numeric() checks the value of the variable and then formats it using the number_format() method. if the value is not numeric, the echo statement prints out the string “Not a numeric value”.
Using Type Casting settype()
The settype() method is used for setting the type of a variable and modify its existing type.
- $variable – This is the variable that needs to be converted
- $type – This is the type you want to convert the variable to
(int)$string; // string into integer (float)$string; // string into float (double)$string; // string into double
Code Example:
// Declare string value $string = '25'; $stringf = '25.99'; $stringd = '25.99'; // Check if string in numaric if (is_numeric($string))< // Convert string to integer using int type cast echo 'Integer Value: '.(int)$string; >else < echo 'Not a numaric value'; >// Check if string in numaric if (is_numeric($stringf))< // Convert string to float using float type cast echo '
Float Value: '.(float)$stringf; >else < echo 'Not a numaric value'; >// Check if string in numaric if (is_numeric($stringf))< // Convert string to float using float type cast echo '
Double Value: '.(double)$stringd; >else
Integer Value: 25 Float Value: 25.99 Double Value: 25.99
Explanation:
In this code, you can observe that typecasting is used for converting the string into an integer. After evaluating whether the given variable has a string value or not using the is_numeric method, the line echo ‘Integer Value: ‘.(int)$string; converts the string into an integer. Similarly, later on in the program, variables are converted to double and float, by mentioning the data type along with the variable name.
Using intval() and floatval() Function
The intval() function is used for returning the integer value of a variable.
It takes two parameters:
- $var – This is the variable that you want to convert into an integer
- $base – This optional parameter specifies the base for conversion. If $var has 0x as a prefix, 16 is taken as the base. If $var starts with 0, 8 is taken as the base
The floatval() method is used for obtaining the float value of a variable. It takes only one parameter $var, that is the value whose float value needs to be determined.
intval($string); // Convert string to integer floatval($string); // Convert string to float
Code Example:
// Declare string value $string = '25.99'; // Check if string in numaric if (is_numeric($string))< // Convert string to integer using intval function echo 'Integer Value: '.intval($string); // Convert string to float using floatval function echo '
Integer Value: '.floatval($string); >else
Integer Value: 25 Integer Value: 25.99
Explanation:
You can see that in the example, the intval() converts the value stored in the $string variable into an integer. Later the same value is converted into a float using the floatval() method.
Performing Mathematical Operations on String Value
Here, no in-built functions are used for a string to be converted to an integer.
By Adding Number «0» to String
Code Example:
Float Value: ' . ($string + 0.00); >else < echo 'Not a numaric value'; >?>
Integer Value: 25.23 Float Value: 25.23
Explanation:
This is one of the easiest ways to convert a string into an integer. In this program, 0 is added to the string, which converts it into a number. By adding the string with 0.00 the value is converted into a float. This conversion is done by PHP automatically.
By Multiply Number «1» to String
Code Example:
Float Value: ' . ($string * 1.00); >else < echo 'Not a numaric value'; >?>
Integer Value: 25.23 Float Value: 25.23
Explanation:
Another simple method for a string to be converted to an integer is by multiplying it by 1. So, the string 25.23 is multiplied by 1 to get an integer value.
Conclusion:
All these methods are applied when you get a number as a string but want to perform some mathematical operations on it. Although the intval(), float(), number_format() and type casting methods are very effective, adding 0 and multiplying 1 to a string is a very fast way to convert it into a number.
- Learn PHP Language
- PHP Interview Questions and Answers
- PHP Training Tutorials for Beginners
- Display Pdf/Word Document in Browser Using PHP
- Call PHP Function from JavaScript
- Call a JavaScript Function from PHP
- PHP Pagination
- Alert Box in PHP
- Php Count Function
- PHP Filter_var ()
- PHP array_push Function
- strpos in PHP
- PHP in_array Function
- PHP strtotime() function
- PHP array_merge() Function
- explode() in PHP
- implode() in PHP
- PHP array_map()
PHP- how to convert string to number?
Are you only trying to remove commas? When you say you want to convert to a number, what specifically do you mean? An integer? A float? A numeric string?
8 Answers 8
You can replace the string ‘,’ to » and then convert into integer by int
NOTE: int is better to use than intval function. It reduces overhead of calling the function in terms of Speed. http://objectmix.com/php/493962-intval-vs-int.html
UPDATED: if comma comes out as a thousands-separator then:
This depends very much on whether , is used as a decimal point or a thousands-separator. In the US, your result would be off by a factor of a thousand — even more if there were two commas.
you can simply replace ‘,’ with »
$newnumber = str_replace(',', '', $val);
I think you just want to remove the , :
'')); $number = intval($val); var_dump($number);
use strtr() instead of str_replace() in case of multiple ,
When I see your code it’s just sting string(5) «19500»
so you can convert to integer like the following
So the result will be int(19500)
$val = "19,500"; $newnumber = intval(str_replace(',', '', str_replace('.', '', $val))); // output : 19500 $val = "19,500.25"; $newnumber = intval(str_replace(',', '', str_replace('.', '', $val))); // output : 1950025
you can edit delimiter that want to replace with balnk string 🙂
$newnumber = preg_match("/[^0-9,. -]/", $val) ? 0 : preg_replace("/[^0-9.-]/", "",$val);
You almost never want to remove both commas and periods, unless what you have isn’t really a number. Doing so throws off the numeric value by several orders of magnitude.
@cHao => Question mentioned that «how to convert string to number?» then if string contain alpha numeric value, it will automatically convert to 0.
No, it’ll automatically stop parsing at the first character that doesn’t belong. So intval(‘19,500’) would be equal to 19. But for integers, you want the decimal point (and everything after it) ignored, not interpreted as more digits. So, intval(‘19500.25’) would be equal to 19500, which is almost certainly the desired result. Your example outputs a number a hundred times the string’s numeric value.
@chao => Yes, you are right . And solution is : $newnumber = preg_match(«/[^0-9,. -]/», $val) ? 0 : preg_replace(«/[^0-9.-]/», «»,$val);
That’d work. mostly. though it differs from the built-in behavior in that any wacky character causes the result to be 0. I’m of two minds about whether that’s a good thing. Depends on whether that degree of strictness is called for, i guess.
How to Convert a String to a Number in PHP
It is possible to convert strings to numbers in PHP with several straightforward methods.
Below, you can find the four handy methods that we recommend you to use.
Applying Type Casting
The first method we recommend you to use is type casting. All you need to do is casting the strings to numeric primitive data types as shown in the example below:
$num = (int) "10"; $num = (double) "10.12"; // same as (float) "10.12"; ?>
The second method is to implement math operations on the strings. Here is how you can do it:
Using intval() or floatval()
The third way of converting a string to a number is using the intval() or intval() functions. These methods are generally applied for converting a string into matching integer and float values.
$num = intval("10"); $num = floatval("10.1"); ?>
Using number_format
number_format() is a built-in PHP function that is used to format numbers with grouped thousands and/or decimal points. It takes one or more arguments and returns a string representation of the formatted number.
Here’s the basic syntax for the number_format() function:
number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," ) : string
Let’s take a closer look at each of the arguments:
- $number : The number you want to format. This can be a float or an integer.
- $decimals (optional): The number of decimal points you want to include. The default value is 0.
- $dec_point (optional): The character to use as the decimal point. The default value is «.» (period).
- $thousands_sep (optional): The character to use as the thousands separator. The default value is «,» (comma).
Here’s an example of how to use number_format() to format a number with two decimal places and a comma as the thousands separator:
$number = 1234567.89; $formatted_number = number_format($number, 2, '.', ','); echo $formatted_number; // Output: 1,234,567.89
In this example, the $number variable contains the number we want to format. We use number_format() to format the number with two decimal places, a period as the decimal point, and a comma as the thousands separator. The resulting string is stored in the $formatted_number variable, which we then output to the screen using echo .
number_format() can be very useful when working with monetary values, where it is common to use a specific format for displaying prices or totals. It can also be used to format other types of numeric data, such as percentages or ratios.
When you pass a string to «number_format()», the function first tries to convert the string to a numeric value. If it can’t be converted, it will return false. Otherwise, it will format the numeric value as described in my previous answer.