Home > Article > Backend Development > How to convert php string to floating point type
3 conversion methods: 1. Add the target type "(float)", "(double)" or "(real)" enclosed in parentheses before the string to be converted, the syntax is "( float) string". 2. Use the floatval() function to obtain the floating point value of a string variable, with the syntax "floatval (string variable)". 3. Use the settype() function to set a string variable to a floating point type, with the syntax "settype(string variable, "float")".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php string conversion Three methods for floating point numbers
Method 1. Add the target type enclosed in parentheses before the string to be converted
The target types are:
(float), (double), (real): Convert to floating point type
Example: Convert string type Convert to float type
<?php $str="23.25"; $float=(float)$str; var_dump($str); var_dump($float); ?>
Method 2. Use floatval() function--floating point conversion function
floatval — Get Floating point value of variable
Example:
<?php $str="3.14"; $float=floatval($str); var_dump($str); var_dump($float); ?>
Method 3: Use settype() function--Type setting function
settype(): used to set a variable to a specified type (the settype() function will change the original type of the variable).
settype ( $var , $type )
$var: The variable to be converted.
#$type: The target type to which the variable is to be converted.
Return value: TRUE when the setting is successful, FALSE when the setting fails.
Just set the second parameter $type
value of the settype() function to "float".
<?php $str="5.14"; var_dump($str); $float=settype($str,"float"); var_dump($str); var_dump($float);//返回值 ?>
Explanation: The value of the second parameter (set type) of the settype() function can be:
"boolean " (or "bool" from PHP 4.2.0 onwards)
"integer" (or "int" from PHP 4.2.0 onwards)
"float" (only available after PHP 4.2.0, "double" used in older versions is now disabled)
"string"
"array"
"object"
"null" (from PHP 4.2.0 Starting)
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to convert php string to floating point type. For more information, please follow other related articles on the PHP Chinese website!