Converts a scalar value to PHP floating-point form.
What Is floatval() in PHP?
Converts a scalar value to PHP floating-point form.
Its syntax is:
floatval(mixed $value): float
Parameters:
$value— Accepted as mixed; required argument.
Return type: float. Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first.
Availability: Core PHP.
Example 1: Basic Usage
<?php
var_dump(floatval("12.75"));
Output:
float(12.75)
Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first.
Example 2: A Different Input
<?php
var_dump(floatval("invalid"));
Output:
float(0)
Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first.
Practical Example: Applying It in a Program
<?php
$prices = ["12.50", "7.25"]; $sum = 0.0; foreach ($prices as $price) { $sum += floatval($price); } echo number_format($sum, 2);
Output:
19.75
Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first.
Important Behavior and Edge Cases
- Key behavior: Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first.
- Environment: Core PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
floatval() | Converts a scalar value to PHP floating-point form. |
doubleval() | doubleval() and floatval() are aliases; both convert values into floats. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic | Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first. |
Key Takeaways
- Converts a scalar value to PHP floating-point form.
- Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first.
- Core PHP.
Summary: Invalid strings can convert to 0 and floats are unsuitable for exact financial arithmetic. Validate inputs first.