我在PHP中有一个浮点数:0.966666666667
我想将它打印成:0.96
我使用了round()和number_format()
,但它们都给了我两个
0.97
有这样的功能吗?
答案 0 :(得分:1)
你可以这样做:
$num = 0.966666;
$num = floor($num * 100) / 100;
答案 1 :(得分:0)
我发现这样做的最好方法是:
//$val - the value to truncate
//$dist - the number of digits after to decimal place to keep
function truncate($val, $dist) {
//get position of digit $dist places after decimal point
$pos = strpos($val,'.');
if($pos !== false) {//if $val is actually a float
//get the substring starting at the beginning
//and ending with the point $dist after the
//decimal, inclusive -- convert to float.
$val = floatval(substr($val, 0, $pos + 1 + $dist));
}
return $val;
}
然后拨打truncate($YOUR_NUM, 2);
。