Mastering PHP’s floatval: Convert Any Variable to Float Easily

This guide explains how PHP's built‑in floatval function converts integers, strings, booleans, and arrays into floating‑point numbers, provides syntax and practical code examples, and highlights important considerations when conversion fails.

php Courses
php Courses
php Courses
Mastering PHP’s floatval: Convert Any Variable to Float Easily

In PHP we often need to cast variables to floating‑point numbers, and the built‑in floatval function makes this straightforward.

Syntax

floatval ( mixed $var ) : float

The function accepts any variable—integer, string, boolean, array, etc.—and attempts to convert it to a float, returning the result.

Examples

// Convert an integer
$int = 10;
$float = floatval($int);
echo $float;          // 10.0
echo gettype($float); // double

// Convert a numeric string
$str = "3.14";
$float = floatval($str);
echo $float;          // 3.14
echo gettype($float); // double

// Convert a string with extra characters
$str = "3.14test";
$float = floatval($str);
echo $float;          // 3.14
echo gettype($float); // double

// Convert a boolean
$bool = true;
$float = floatval($bool);
echo $float;          // 1.0
echo gettype($float); // double

// Convert an array (first element is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float;          // 5.0
echo gettype($float); // double

These examples show that integers, numeric strings, booleans, and even arrays can be easily turned into floats with floatval.

Be aware that if the value cannot be interpreted as a number—e.g., a non‑numeric string— floatval returns 0, so you should validate inputs before conversion.

In summary, floatval is a handy tool for converting variables to floating‑point numbers, useful in calculations, monetary operations, and other numeric processing tasks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingPHPtype conversionfloatvalnumeric casting
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.