OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Float In PHP

Code snippet for how to Convert Variable From String To Float In PHP with sample and detail explanation

In this article, we will be exploring how to convert a variable from string to float in PHP. This basic data type manipulation is integral in dealing with numbers in string format while performing mathematical computations.

Code snippet

Here is a simple PHP code snippet for converting a string into a float:

<?php
$strVar = "34.87";
$floatVar = (float)$strVar;

echo $floatVar;
?>

Code Explanation

The PHP script above outlines a seamless approach to convert a string variable ($strVar) into a float.

In the first line, a string variable $strVar is defined with the value “34.87”. This is essentially a string containing a number.

$strVar = "34.87";

The magic happens in the second line - this is where we’re converting the string to a float. In PHP, casting a string to float can be done by prefixing the variable with (float). So, $floatVar = (float)$strVar; converts the string variable into a float variable.

$floatVar = (float)$strVar;

Finally, the echo statement is used to output the value of the $floatVar variable. If the variable casting was successful, the $floatVar will now hold the float value 34.87 instead of the string “34.87”.

echo $floatVar;

With this, we’ve successfully converted a string into a float in PHP. This process is crucial when handling numeric data that might be passed as a string but should be processed as a numerical value, such as user input or information taken from a database.

php