Home >Backend Development >PHP Problem >What are the functions for converting numeric values in php?
The conversion functions include: 1. intval(), which can convert a string into an integer value, the syntax is "intval($str)"; 2. floatval(), which can convert a string into a floating point Type value, syntax "floatval($str)"; 3. settype(), you can set the variable to an integer or floating point value, syntax "settype($str,"integer")" or "settype($str,"float ")"; 4. base_convert().
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
1. intval() function--integer Type conversion function
intval() function is used to obtain the integer value of a variable.
intval() function returns the integer value of variable var by using the specified base conversion (default is decimal). intval() cannot be used with object, otherwise an E_NOTICE error will be generated and 1 will be returned.
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $int = intval($str); echo $int."<br>"; echo '变量 $int 的类型为:' . gettype($int) . '<br>'; ?>
2. floatval() function--floating point conversion function
floatval — Get the floating point value of a variable
Example:
<?php $str="3.14"; $float=floatval($str); var_dump($str); var_dump($float); ?>
3. settype() function
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; settype($str,"integer"); echo $str."<br>"; echo '修改后的类型为:' . gettype($str) . '<br>'; ?>
Description:
The settype() function is used to set the variable $var to the specified $type type. Syntax:
settype ( $var ,$type )
$type Settable values:
"boolean" (or "bool", starting from PHP 4.2.0)
"integer" (or "int" since PHP 4.2.0)
"float" (only available since PHP 4.2.0, For "double" used in older versions now deprecated)
"string"
"array"
"object"
4. Use the base_convert() function
base_convert() function to convert numbers between any bases, just set "bindec(hex string, 16, 10)" to convert hexadecimal numbers into decimal numbers.
<?php echo base_convert("1e", 16, 10) . "<br>"; echo base_convert("a", 16, 10) . "<br>"; echo base_convert("11ff", 16, 10) . "<br>"; echo base_convert("cceeff", 16, 10); ?>Description: base_convert() function converts numbers between arbitrary bases. Syntax:
base_convert(number,frombase,tobase);
PHP Video Tutorial"
The above is the detailed content of What are the functions for converting numeric values in php?. For more information, please follow other related articles on the PHP Chinese website!