In this PHP tutorial, you shall learn how to convert a given string to a float value using typecasting or floatval() function, with example programs.
PHP – Convert string to float
To convert string to float in PHP, you can use Type Casting technique or PHP built-in function floatval().
In this tutorial, we will go through each of these methods and learn how to convert contents of a string to a float value.
Convert String to Float using Type Casting
To convert string to floating point number using Type Casting, provide the literal (float) along with parenthesis before the string literal. The expression returns float value of the string.
The syntax to type cast string to float number is
$float_value = (float) $string;
Example
In the following example, we will take a string with floating point number content, and convert the string into float using type casting.
PHP Program
<?php
$string = "3.14";
$float_value = (float) $string;
echo $float_value;
?>
Output
