Conversion method: 1. Add the target type "(float)", "(double)" or "(real)" enclosed in parentheses before the string variable; 2. Use "floatval(character String)" statement; 3. Use the "settype(string variable, "float")" statement.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php string conversion For floating-point data
Method 1: Add the target type enclosed in parentheses "(float)
", "before the string variable (double)
" or "(real)
"
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $float1 = (float)$str; echo '变量 $float1 的类型为:'.gettype($float1).'<br>'; $float2 = (double)$str; echo '变量 $float2 的类型为:'.gettype($float2).'<br>'; $float3 = (real)$str; echo '变量 $float3 的类型为:'.gettype($float3).'<br>'; ?>
floatval(): used to obtain the floating point value of the variable;
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $float = floatval($str); echo '变量 $float 的类型为:'.gettype($float).'<br>'; ?>
Output result:
Method 3: Use the settype() functionThe settype() function is used to set the type of a variable.
Syntax:
settype (mixed &$var, string $type)
$type: The possible values of type are.
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456'; $float = settype($str, 'float');; echo '$str 的类型为:'.gettype($str).'<br> $float 的类型为:'.gettype($float); ?>
Output:
Note: The settype() function will change the original type of the variable. If the setting is successful, it will return TRUE and if it fails, it will return FALSE.
Recommended learning: "
PHP Video TutorialThe above is the detailed content of How to convert php string to floating point data. For more information, please follow other related articles on the PHP Chinese website!