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.

Watch a course Learn object oriented PHP

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:

<?php

$num = (int) "10"; 
$num = (double) "10.12"; 
// same as (float) "10.12";

?>
Performing Math Operations

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

<?php

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

?>

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:

<?php

$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:

<?php

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