floatval

Converts a value to a float, reading the leading numeric part of a string.

Signature
floatval(mixed $value): float
  • Added in PHP 4.2.0

Parameters

ParameterTypeDescription
$valuemixedThe value being converted to a float. May be any scalar type; objects should not be passed.

Return value

floatThe float value of the given variable. Empty arrays return 0, non-empty arrays return 1.

Errors

Passing an object raises an E_WARNING (E_NOTICE before PHP 8.0) and returns 1.0.

Changelog

  • PHP 8.0.0The error level raised when converting from an object changed from E_NOTICE to E_WARNING.

floatval() is the function form of the (float) cast. Given a string it reads an optional sign, digits, one decimal point and an optional exponent from the front of the string and stops at the first character that cannot be part of a number. Leading whitespace is skipped; trailing junk is ignored silently.

That leniency is the whole story of this function. floatval('12.5 kg') is 12.5, floatval('1e3') is 1000.0, and floatval('price 9.99') is 0.0 because the very first character already fails. There is no error and no way to tell a parsed 0 from a failed parse.

When to reach for it

Use it when you already trust the input and just want a number out of a string that may carry a unit or stray spaces — a scraped measurement, a legacy CSV column, a config value. Use it as a callable with array_map() to convert a whole column at once.

Do not use it to validate. If the value has to be a real number, check with is_numeric() or filter_var($v, FILTER_VALIDATE_FLOAT) first, which return false instead of quietly producing 0.0. And remember the result is a binary float: never compare it to another float with ===, and never store money in it without rounding.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Pulling a numeric measurement out of a scraped string such as '12.5 kg' or '3.4 GHz'
  • Converting a CSV column of price strings to floats in one array_map pass before summing
  • Coercing a JSON or database value that may arrive as a numeric string into a typed float property

Frequently asked questions

What is the difference between floatval() and (float)?

None — they perform the same conversion. floatval() exists so the conversion can be passed as a callable to functions like array_map().

Why does floatval() return 0 for my string?

Because the string does not begin with a number; floatval() reads from the left and stops at the first character that cannot be part of a number. Strings like 'price 9.99' or '$5' return 0.0.

How do I tell whether floatval() actually parsed something?

You cannot, from the result alone — a failed parse and a real zero both give 0.0. Check the input first with is_numeric() or filter_var($v, FILTER_VALIDATE_FLOAT), which returns false on failure.

More examples

Parsing a formatted price safely

Stripping the currency symbol and thousands separators first gives 1299.50. Passing the raw string straight to floatval() returns 0.0, because the leading '$' stops the parse immediately — a silent failure with no warning.

Example · php
<?php
$raw   = '$1,299.50';
$clean = floatval(str_replace(['$', ','], '', $raw));

printf("%.2f\n", $clean);
var_dump($clean === 1299.5);

// Without cleaning first:
var_dump(floatval($raw));

Validate before you convert

'abc' and '' both convert to 0.0, which is indistinguishable from a genuine zero. The is_numeric() column is the only thing that separates a real number from a failed parse, which is why validation has to happen before the conversion.

Example · php
<?php
foreach (['42', '42.0', '4.2e1', 'abc', ''] as $v) {
    $f = floatval($v);
    printf("%-6s -> %-6s numeric=%s\n",
        var_export($v, true),
        var_export($f, true),
        var_export(is_numeric($v), true)
    );
}

Floats are approximate

0.1 + 0.2 is not exactly 0.3 in binary floating point, so the strict comparison is false and the 20-decimal print shows the drift. Compare floats with a tolerance such as PHP_FLOAT_EPSILON instead of === .

Example · php
<?php
$a = floatval('0.1');
$b = floatval('0.2');

var_dump($a + $b === 0.3);
echo number_format($a + $b, 20), "\n";
var_dump(abs(($a + $b) - 0.3) < PHP_FLOAT_EPSILON);

Discussion

  • Be the first to comment on this lesson.