How do I convert a string to a number in PHP?
In JavaScript, converting a string like '2.34' into a numeric type is as simple as passing it to Number(). You might expect PHP to offer an identical one-liner function that handles integers and floating-point numbers with equal grace. While PHP does provide built-in functions for this task, relying on them without understanding the underlying mechanics can lead to subtle bugs, particularly when dealing with locale-specific formatting or precision loss.
The most direct equivalent to JavaScript's Number() is the (int) cast operator or the (float) cast operator. These are unary operators that take a variable and force its type conversion. If you strictly need an integer, casting a string like '2' works as expected:
$input = '2';
$number = (int) $input; // Result: 2
However, attempting to cast a decimal string directly to an integer truncates the fractional part rather than rounding it. The string '2.34' becomes 2, and '0.9' becomes 0. This behavior is deterministic but often contrary to what developers expect when they simply want "a number" regardless of its scale.
For floating-point numbers, which cover your use cases for values like '2.34' or '0.234343', you should cast the string to a float:
$input = '2.34';
$number = (float) $input; // Result: 2.34
$input = '0.3454545';
$number = (float) $input; // Result: 0.3454545
This approach is efficient and readable. The PHP engine parses the string representation of the number and constructs an IEEE 754 double-precision floating-point number. It handles the conversion automatically, stripping away quotes and returning a standard numeric type that can be used in arithmetic operations without further casting.
There is, however, a significant pitfall to consider: locale separators. The examples provided assume standard dot notation (.) for decimals. If your application environment uses a comma (,) as the decimal separatorâcommon in many European localesâthe cast will fail to produce the expected numeric value. A string like '2,34' cast to (float) will result in 0 because PHP interprets the comma as an invalid character in this context.
To handle data that might arrive with various formatting styles or if you are ingesting user input directly from a database stored in a specific locale, you must normalize the string first. The number_format() function can be used to enforce dot notation, but it is often better to rely on strict validation or regex cleaning before casting:
$input = '2,34'; // Comma decimal
$normalized = str_replace(',', '.', $input);
$number = (float) $normalized; // Result: 2.34
Alternatively, you can use the filter_var() function with the FILTER_FLOAT flag. This method offers a safety net by throwing an exception or returning a filter failure if the string cannot be converted due to invalid characters or format issues. It is slightly more verbose but provides explicit error handling capabilities that simple casting lacks:
$input = '2.34';
$number = filter_var($input, FILTER_FLOAT);
// Returns 2.34 on success
When building robust applications, especially in a framework like Laravel, you might find yourself needing to ensure type consistency across your data models. While casting is perfect for simple scripts, frameworks often provide helper methods or validation rules that abstract these concerns away. For instance, defining validation rules ensures that only correctly formatted numbers reach your logic layer, preventing silent failures caused by malformed strings.
Ultimately, the choice between direct casting and filter_var depends on your error tolerance. If you expect clean data from a trusted API or database, (float) is the most performant option. If the source of the string is untrusted or varies in format, explicit normalization or validation is necessary to maintain data integrity.