PHP 数减去同数不等于0
PHP number minus same number not equal 0
我正在尝试使用 PHP 从 119.7 减去 119.7,但结果不是预期的 (-1.4210854715202E-14),预期结果是 0
- Doc1 RestToPay = 171
- Doc2 RestToPay = 119.7
这是我的代码:
$TotalAmountToPay = 290.7;
foreach($Docs as $Doc){
$RestToPay = $Doc['RestToPay'];
if($TotalAmountToPay <= 0){
break;
}
$TotalAmountToPay = $TotalAmountToPay - $RestToPay;
if($TotalAmountToPay >= 0){
echo "OK: ".$TotalAmountToPay;
}else{
echo "Done: ".$TotalAmountToPay;
}
}
我得到的输出:
- 还行:119.7
- 完成:-1.4210854715202E-14
这些数字的存储和转换方式似乎有些不同。您始终可以使用 round()
函数,它应该可以满足您的需求。所以也许试试这个:
$TotalAmountToPay = 290.7;
foreach($Docs as $Doc){
$RestToPay = $Doc['RestToPay'];
if($TotalAmountToPay <= 0){
break;
}
$TotalAmountToPay = $TotalAmountToPay - $RestToPay;
if($TotalAmountToPay >= 0){
echo "OK: ".round($TotalAmountToPay,4);
}else{
echo "Done: ".round($TotalAmountToPay,4);
}
}
应该会有帮助。
$TotalAmountToPay = 290.7;
foreach($Docs as $Doc){
$RestToPay = $Doc['RestToPay'];
if($TotalAmountToPay <= 0){
break;
}
$TotalAmountToPay = round($TotalAmountToPay,2) - round($RestToPay,2);
if($TotalAmountToPay >= 0){
echo "OK: ".$TotalAmountToPay;
}else{
echo "Done: ".$TotalAmountToPay;
}
}
我正在尝试使用 PHP 从 119.7 减去 119.7,但结果不是预期的 (-1.4210854715202E-14),预期结果是 0
- Doc1 RestToPay = 171
- Doc2 RestToPay = 119.7
这是我的代码:
$TotalAmountToPay = 290.7;
foreach($Docs as $Doc){
$RestToPay = $Doc['RestToPay'];
if($TotalAmountToPay <= 0){
break;
}
$TotalAmountToPay = $TotalAmountToPay - $RestToPay;
if($TotalAmountToPay >= 0){
echo "OK: ".$TotalAmountToPay;
}else{
echo "Done: ".$TotalAmountToPay;
}
}
我得到的输出:
- 还行:119.7
- 完成:-1.4210854715202E-14
这些数字的存储和转换方式似乎有些不同。您始终可以使用 round()
函数,它应该可以满足您的需求。所以也许试试这个:
$TotalAmountToPay = 290.7;
foreach($Docs as $Doc){
$RestToPay = $Doc['RestToPay'];
if($TotalAmountToPay <= 0){
break;
}
$TotalAmountToPay = $TotalAmountToPay - $RestToPay;
if($TotalAmountToPay >= 0){
echo "OK: ".round($TotalAmountToPay,4);
}else{
echo "Done: ".round($TotalAmountToPay,4);
}
}
应该会有帮助。
$TotalAmountToPay = 290.7;
foreach($Docs as $Doc){
$RestToPay = $Doc['RestToPay'];
if($TotalAmountToPay <= 0){
break;
}
$TotalAmountToPay = round($TotalAmountToPay,2) - round($RestToPay,2);
if($TotalAmountToPay >= 0){
echo "OK: ".$TotalAmountToPay;
}else{
echo "Done: ".$TotalAmountToPay;
}
}