如何使用 PHP 中的 round() 和 number_format() 进行完美计算
How to get the perfect calculation using the round() and number_format() in PHP
我有两个计算,其答案应该是这样的。
每加仑英里数:5.22
每公里垃圾:45.09
但我得到的答案是 MPG(5.31817920134) 和 LPK(44.2283704264)。
这是我的代码。谁能帮忙解决这个问题?
$fuelTotal = 74 + 91.5 + 128;
$odometerTotal = 161.406 + 201.187 + 289.407;
$fuelMPG = number_format(($odometerTotal * 0.621371) / (round($fuelTotal) / 3.78541), 2, '.', '');
$fuelLPK = number_format((round($fuelTotal) / $odometerTotal) * 100, 2, '.', '');
这里。我也测试了你的代码,它只给出了 2 的四舍五入。答案如期而至。
以下代码用于四舍五入到小数点后两位。
<?php
$fuelTotal = 74 + 91.5 + 128;
$odometerTotal = 161.406 + 201.187 + 289.407;
$fuelMPG = number_format(($odometerTotal * 0.621371) / (round($fuelTotal) / 3.78541), 2, '.', '');
$fuelLPK = number_format((round($fuelTotal) / $odometerTotal) * 100, 2, '.', '');
echo round($fuelLPK, 2); //Will Round off LPK to 2 decimal points.
echo round($fuelMPG , 2); //Will Round off MPG to 2 decimal points.
?>
我有两个计算,其答案应该是这样的。
每加仑英里数:5.22
每公里垃圾:45.09
但我得到的答案是 MPG(5.31817920134) 和 LPK(44.2283704264)。 这是我的代码。谁能帮忙解决这个问题?
$fuelTotal = 74 + 91.5 + 128;
$odometerTotal = 161.406 + 201.187 + 289.407;
$fuelMPG = number_format(($odometerTotal * 0.621371) / (round($fuelTotal) / 3.78541), 2, '.', '');
$fuelLPK = number_format((round($fuelTotal) / $odometerTotal) * 100, 2, '.', '');
这里。我也测试了你的代码,它只给出了 2 的四舍五入。答案如期而至。
以下代码用于四舍五入到小数点后两位。
<?php
$fuelTotal = 74 + 91.5 + 128;
$odometerTotal = 161.406 + 201.187 + 289.407;
$fuelMPG = number_format(($odometerTotal * 0.621371) / (round($fuelTotal) / 3.78541), 2, '.', '');
$fuelLPK = number_format((round($fuelTotal) / $odometerTotal) * 100, 2, '.', '');
echo round($fuelLPK, 2); //Will Round off LPK to 2 decimal points.
echo round($fuelMPG , 2); //Will Round off MPG to 2 decimal points.
?>