How do I convert a string to a number in PHP?

Nadia S.

The Problem

How do I convert a string to a number in PHP?

The Solution

We’ll take a look at four ways to convert numeric strings into numbers in PHP:

  • Dynamic typing.
  • The intval() and floatval() functions.
  • Type casting with (int) and (float).
  • The settype() function.

Dynamic Typing

PHP is a dynamically typed language that recognizes numerical strings. You can perform mathematical operations directly with numeric strings. When we add 5 to '3.14', we get a float of 8.14 as a result:

Click to Copy
$string = '3.14'; $mySum = $string + 5; var_dump($mySum);

Output:

Click to Copy
// we get a float of 8.14 float(8.14)

The intval() and floatval() Functions

You can pass a numeric string literal into the intval() function to get the integer version or the floatval() function to get the float version. For example:

Click to Copy
// convert '3.9' to int and float $myFloat = floatval('3.9'); $myInt = intval('3.9'); // echo out type and value echo '$myFloat is ',var_dump($myFloat); echo '$myInt is ',var_dump($myInt);

We get an output of 3.9 as our float value. Note how casting a number to an integer won’t round it off, as'3.9' becomes 3:

Click to Copy
$myFloat is float(3.9) $myInt is int(3)

Type Casting with (int) and (float)

Make the (int) or (float) declaration in front of a numeric string literal to type cast it accordingly. For example:

Click to Copy
$castFloat = (float) '3.9'; $castInt = (int) '3.9'; echo '$castFloat is ',var_dump($castFloat); echo '$castInt is ',var_dump($castInt);

Output:

Click to Copy
$castFloat is float(3.9) $castInt is int(3)

The settype() Function

You can change the data type of the original numeric string into a float or integer using the settype() function. This is useful in cases where you don’t want to create a new variable to hold a value of a different data type.

In this example, we pass in the variable $pi and the datatype 'float' as arguments into the settype() function:

Click to Copy
$pi = '3.14'; settype($pi, "float"); var_dump($pi);

The $pi value is now a float.

Click to Copy
float(3.14)

Here we pass in 'integer' to change our $num variable to an integer:

Click to Copy
$num = '4.5'; settype($num, 'integer'); var_dump($num);

Output:

Click to Copy
int(4)

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.