方法:1、在值之前加上“(int)”或“(integer)”,例“3.14(int)”;2、用intval()函数,语法“intval(值)”;3、用ceil()函数,语法“ceil(值)”;4、用floor函数,语法“floor(值)”。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

php将值转为整数

1、在值之前加上“(int)”或“(integer)”

<?php
$str = '123.456abc';
$int = (int)$str;
echo $int."<br>";

$float = 3.14;
$int = (integer)$float;
echo $int."<br>";
?>

1.png

2、使用intval()函数

<?php
$str = '123.456abc';
$int = intval($str);
echo $int."<br>";

$float = 5.64;
$int = intval($float);
echo $int."<br>";

$bool = true;
$int = intval($bool);
echo $int."<br>";
?>

2.png

3、使用ceil()函数

ceil()函数用于向上取整,有小数就整数部分加1

<?php
header("Content-type:text/html;charset=utf-8"); 
$num = 123.456;
$int = ceil($num);
echo '变量 $int 的类型为:'.gettype($int).'<br>';
echo $int;
?>

3.png

4、使用floor函数

floor函数用于向下取整

<?php
header("Content-type:text/html;charset=utf-8"); 
$num = 123.456;
$int = floor($num);
echo '变量 $int 的类型为:'.gettype($int).'<br>';
echo $int;
?>

4.png


php怎么将值转为整数