Method: 1. Add "(float)" before the variable or value, for example "(float)123"; 2. Use the floatval() function, the syntax is "floatval(variable)"; 3. Use " "operator, the syntax is "variable 0.0"; 4. Use the round() function, the syntax is "round(variable, 2)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
PHP will change a variable Several methods of converting to float
First of all, PHP is the best language. There are many methods for data types. Below are examples one by one. If there are any deficiencies, please feel free to add
$str = 'NaN'; // 强制类型转换----float只能转换前面带数字的字符串 echo (float) $str; echo '<br/>'; //floatval() — 获取变量的浮点值 echo floatval($str); echo '<br/>'; // 做一个加法运算也可以达到效果 echo ($str + 0.0); echo '<br/>'; // round四舍五入,返回了0,但并没有保留2位小数 echo round($str,2); echo '<br/>';
Explanation:
1. Forced type conversion--when you want to convert The variable is preceded by the target type enclosed in parentheses
. The PHP data types allowed for conversion are:
(int) , (integer): Convert to integer
##(float), (double), (real): Convert to floating point type
2, floatval()
floatval ( mixed $var ) : float
3. round()
The round() function rounds floating point numbers. Syntaxround(number,precision,mode);
Description | |
---|---|
number | Required. Specifies the value to be rounded.|
precision | Optional. Specifies the number of digits after the decimal point. Default is 0, can also be negative.|
mode | Optional. Specifies a constant representing the rounding mode:
|
PHP Video Tutorial"
The above is the detailed content of How to convert variables to float in php. For more information, please follow other related articles on the PHP Chinese website!