Home >Backend Development >PHP Problem >How to cast value to float in php
Method: 1. Add the target type "(float)" enclosed in parentheses before the variable, the syntax is "(float)$val"; 2. Use floatval(), the syntax "floatval($val )"; 3. Use settype(), the syntax is "settype($val, "float")".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php forces the value Type conversion to float
Method 1: Add the target type enclosed in parentheses "(float)
"## before the variable to be converted #
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $float = (float)$str; echo $float."<br>"; echo '变量 $float 的类型为:' . gettype($float) . '<br>'; ?>
Method 2: Use floatval() function
floatval(): used to obtain the floating point value of a variable;<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $float = floatval($str); echo $float."<br>"; echo '变量 $float 的类型为:' . gettype($float) . '<br>'; ?>Output result:
Method 3: Use settype() function
Syntax:The
settype ( $var ,$type )settype() function is used to set the variable $var to the specified $type type. Example
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; settype($str,"float"); echo $str."<br>"; echo '修改后的类型为:' . gettype($str) . '<br>'; ?>Output result: Description: The settable value of $type
PHP Video Tutorial"
The above is the detailed content of How to cast value to float in php. For more information, please follow other related articles on the PHP Chinese website!