PHP四舍五入小数不工作


php round up decimals not working

我有一段代码,但它没有响应正确的答案,或者以正确的格式。我尝试了round函数,但是没有显示任何东西

here is my code
$total_per_year = 308790;
$fat = $total_per_year / 3500;
echo $fat;

它目前显示它为0.088,但正确答案是88.2257142857

我怎么做才能使它四舍五入到88.2

round函数需要如下两个参数:

echo round($fat,1);

第二个参数是您需要的小数位数。

我以前遇到过round不按预期工作的问题,我不得不使用number_format:

echo number_format((float)$fat,1,'.','');

1为所需的小数点,句号为小数分隔符,"为千位分隔符

使用round()

echo round($fat, 1); //second argument is precision eg. decimals

查看文档:http://dk1.php.net/round

好了,我现在算出来了。我知道我一直得到"0.088"。这是错误的。

这是因为我有这样的

$total_per_day = number_format($total_per_cup * $number_of_cups);
$total_per_year = number_format($total_per_day * 365);
$fat = round($total_per_year / 3500, 1);
echo $fat;
echo $total_per_year;

是正确的代码。

$total_per_cup = $type_calorie + $milk_calorie + $sugar_calorie;
$total_per_day = $total_per_cup * $number_of_cups;
$total_per_year = $total_per_day * 365;
$fat = $total_per_year / 3500;

echo json_encode(array('total'=> number_format($total_per_year) , 'perday' => number_format($total_per_day), 'fat'=> round($fat, 1)));