How to Convert a String to a Number in PHP

  1. Applying Type Casting
  2. Performing Math Operations
  3. Using intval() or floatval()
  4. Using number_format

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.

A. 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";

B. Performing Math Operations

The second method is to implement math operations on the strings. Here is how you can do it:

$num = "10" + 1;
$num = floor("10.1");

C. 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.

Here is an example:

$num = intval("10"); 
$num = floatval("10.1");

D. Using number_format

Another way of converting a string to a number is by using the number_format function. It will return the formatted number, otherwise, will show you E_WARNING.

Here is an example of using the number_format function:

<?php
  
$num = "1000.314";
  
// Convert string in number using 
// number_format(), function
echo number_format($num), "\n";
  
// Convert string in number using 
// number_format(), function
echo number_format($num, 2);
?>

In this snippet, we represented to you four different and handy ways to convert a string to a number. After reading and checking out the examples, you can choose the one that is more suitable for your project.


Do you find this helpful?

Related articles