Question

How to Convert a String to a Number in PHP

phpcastingtype-conversion

Question

I want to convert string values such as '3', '2.34', and '0.234343' into numeric values in PHP.

In JavaScript, we can use Number(). Is there a similar way to do this in PHP?

$values = ['2', '2.34', '0.3454545'];

Expected results:

InputOutput
'2'2
'2.34'2.34
'0.3454545'0.3454545

Short Answer

By the end of this page, you will understand how PHP converts strings to numbers, when to use (int) or (float), how PHP handles numeric strings automatically, and how to validate input safely before converting it.

Concept

In PHP, converting a string to a number is usually done with type casting or by letting PHP perform automatic type juggling.

A string like '2' can become an integer, and a string like '2.34' can become a float. The main tools are:

  • (int) for whole numbers
  • (float) for decimal numbers
  • is_numeric() to check whether a string can be interpreted as a number

Why this matters

In real applications, numbers often arrive as strings:

  • form inputs from users
  • query parameters in URLs
  • JSON payloads from APIs
  • CSV or database imports

Even if a value looks like a number, PHP may still treat it as a string until you convert or validate it. Understanding conversion helps you avoid bugs in calculations, comparisons, and validation logic.

Important behavior in PHP

PHP does not have a direct equivalent to JavaScript's Number() function with the exact same role and style. Instead, PHP commonly uses casting:

$intValue = (int) '2';
$floatValue = (float) '2.34';

If you want PHP to choose between integer and float based on the input, you typically inspect the string first and then cast accordingly.

Mental Model

Think of a string number as a label on a box.

  • '2' is a box labeled 2
  • '2.34' is a box labeled 2.34

PHP can read the label and turn it into an actual numeric value you can calculate with. But you must tell PHP what kind of numeric box you want:

  • an integer box for whole numbers
  • a float box for decimals

If you choose the wrong box, you may lose information. For example, casting '2.34' to (int) gives 2, because integers do not keep decimal parts.

Take Quiz

Syntax and Examples

Basic conversion with casting

$whole = (int) '2';
$decimal = (float) '2.34';

var_dump($whole);   // int(2)
var_dump($decimal); // float(2.34)

Casting is the most common and direct way to convert strings to numbers in PHP.

Let PHP choose based on the string

If you want '2' to become 2 and '2.34' to become 2.34, you can inspect the value:

function toNumber(string $value): int|float {
    return str_contains($value, '.') ? (float) $value : (int) $value;
}

var_dump(toNumber('2'));         // int(2)
var_dump(toNumber('2.34'));      // float(2.34)
var_dump(toNumber('0.3454545')); // float(0.3454545)

This works well for simple decimal strings.

Safer conversion with validation

function safeToNumber(string $value): int|float|null {
    if (!is_numeric($value)) {
        return null;
    }

    return str_contains($value, '.') ? (float) $value : (int) $value;
}

var_dump(safeToNumber('25'));     // int(25)
var_dump(safeToNumber('7.5'));    // float(7.5)
var_dump(safeToNumber('hello'));  // null

Use is_numeric() when the value may come from users or external systems.

Automatic conversion in expressions

PHP often converts numeric strings automatically during math operations:

$value = '2.5';
$result = $value + 1;

var_dump($result); // float(3.5)

This can be convenient, but explicit conversion is usually clearer and safer.

Step by Step Execution

Consider this example:

$value = '2.34';

if (is_numeric($value)) {
    $number = str_contains($value, '.') ? (float) $value : (int) $value;
    var_dump($number);
}

Step-by-step

  1. $value = '2.34';

    • PHP stores the value as a string.
  2. is_numeric($value)

    • PHP checks whether the string can be interpreted as a number.
    • '2.34' is numeric, so the condition is true.
  3. str_contains($value, '.')

    • PHP checks whether the string contains a decimal point.
    • '2.34' does contain ..
  4. (float) $value

    • Because the string has a decimal point, it is cast to a float.
    • $number becomes 2.34.
  5. var_dump($number)

    • Output:
float(2.34)

Another trace

$value = '2';
$number = str_contains($value, '.') ? (float) $value : (int) $value;
var_dump($number);
  • The string does not contain a decimal point.
  • PHP uses (int) $value.
  • Output:
int(2)

Real World Use Cases

String-to-number conversion appears in many common PHP tasks:

Form handling

$age = (int) $_POST['age'];
$price = (float) $_POST['price'];

HTML forms send values as strings, even when users type numbers.

Query parameters

$page = (int) $_GET['page'];
$discount = (float) $_GET['discount'];

Values from URLs arrive as strings and often need conversion.

API data

When reading JSON or external API data, a number may sometimes be delivered as a string:

$data = ['amount' => '19.99'];
$amount = (float) $data['amount'];

CSV import

$row = ['quantity' => '12', 'unit_price' => '4.50'];
$quantity = (int) $row['quantity'];
$unitPrice = (float) $row['unit_price'];
$total = $quantity * $unitPrice;

Imported data is often textual and must be converted before calculations.

Take Quiz

Real Codebase Usage

In real projects, developers usually combine conversion with validation and clear intent.

Pattern: validate before converting

if (!is_numeric($input)) {
    throw new InvalidArgumentException('Expected a numeric value.');
}

$number = (float) $input;

This prevents bad input from silently producing incorrect values.

Pattern: use integers for count-like values

$userId = (int) $request['user_id'];
$quantity = (int) $request['quantity'];

Use integers for IDs, counts, page numbers, and indexes.

Pattern: use floats for decimal values

$weight = (float) $request['weight'];
$rating = (float) $request['rating'];

Use floats when decimal precision is needed.

Pattern: guard clauses

function parsePrice(string $value): float {
    if (!is_numeric($value)) {
        throw new InvalidArgumentException('Invalid price');
    }

    return (float) $value;
}

Guard clauses keep functions easy to read by rejecting invalid input early.

Pattern: explicit conversion instead of relying on type juggling

$total = (float) $subtotal + (float) $tax;

This is clearer than relying on PHP to convert both values automatically during addition.

Common Mistakes

1. Using (int) on decimal strings

Broken example:

$value = '2.34';
var_dump((int) $value); // int(2)

Problem:

  • (int) removes the decimal part.

Fix:

$value = '2.34';
var_dump((float) $value); // float(2.34)

2. Converting invalid strings without checking

Broken example:

$value = 'abc';
var_dump((int) $value);   // int(0)
var_dump((float) $value); // float(0)

Problem:

  • Invalid input may become 0, which can hide bugs.

Fix:

if (is_numeric($value)) {
    $number = (float) $value;
} else {
    echo 'Invalid number';
}

3. Assuming all numeric strings should be integers

Broken example:

$value = '0.3454545';
$number = (int) $value;
var_dump($number); // int(0)

Problem:

  • The decimal part is lost completely.

Fix:

$number = (float) $value;
var_dump($number); // float(0.3454545)

4. Relying too much on automatic conversion

Broken example:

$value = '10 apples';
$result = $value + 5;

Problem:

  • Mixed strings can produce confusing results or warnings depending on PHP version and context.

Fix:

  • Validate input first.
  • Convert explicitly.

5. Ignoring whitespace and formatting issues

$value = ' 2.5 ';

This may still be numeric in many cases, but input should be cleaned when needed:

$value = trim($value);
if (is_numeric($value)) {
    $number = (float) $value;
}

Comparisons

ApproachExampleResultBest for
Integer cast(int) '2'2Whole numbers only
Float cast(float) '2.34'2.34Decimal values
Automatic conversion'2.34' + 02.34Quick expressions, less explicit
Validation + castis_numeric($v) ? (float) $v : nullSafe conversionUser input and external data

(int) vs (float)

Feature(int)(float)
Keeps decimalsNoYes
Suitable for countsYesSometimes
Suitable for prices or measurementsNoYes
Example(int) '2.9' => 2(float) '2.9' => 2.9

Explicit conversion vs automatic conversion

StyleExampleAdvantageDrawback
Explicit(float) $valueClear and predictableSlightly more code
Automatic$value + 0ShortLess readable and easier to misuse
Take Quiz

Cheat Sheet

Quick conversion rules

(int) '2'        // 2
(float) '2.34'   // 2.34
(double) '2.34'  // 2.34 (same as float)

Check before converting

is_numeric('2');      // true
is_numeric('2.34');   // true
is_numeric('abc');    // false

Convert based on content

$number = str_contains($value, '.') ? (float) $value : (int) $value;

Safe helper

function toNumber(string $value): int|float|null {
    $value = trim($value);

    if (!is_numeric($value)) {
        return null;
    }

    return str_contains($value, '.') ? (float) $value : (int) $value;
}

Key rules

  • Use (int) for whole numbers.
  • Use (float) for decimals.
  • Use is_numeric() for validation.
  • Do not rely blindly on automatic type juggling.
  • Casting invalid strings may produce 0 or other confusing results.

Edge case reminder

(int) '2.99'   // 2
(float) '2'    // 2.0

A float can represent whole numbers too, but its type will still be float.

FAQ

Is there a Number() function in PHP like JavaScript?

Not exactly. In PHP, the usual approach is type casting with (int) or (float).

How do I convert a string to an integer in PHP?

Use:

$number = (int) '42';

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

Use:

$number = (float) '3.14';

How can I check whether a string is numeric before converting it?

Use is_numeric():

is_numeric('123');   // true
is_numeric('12.5');  // true
is_numeric('abc');   // false

What happens if I cast '2.34' to int in PHP?

PHP drops the decimal part, so the result is 2.

Should I use automatic conversion or explicit casting?

Explicit casting is usually better because it is clearer and easier to maintain.

Can form input numbers still be strings in PHP?

Yes. Data from forms is usually received as strings, even when it looks numeric.

Take Quiz

Mini Project

Description

Build a small PHP utility that reads an array of string values and converts only the valid numeric ones into PHP numbers. This demonstrates validation, integer vs float conversion, and how to safely ignore invalid input.

Goal

Create a function that accepts string values, converts valid numeric strings to int or float, and skips invalid entries.

Requirements

Requirement 1

Take Quiz

Keep learning

Related questions

View more