舍入问题不正确,向下舍入而不是向上舍入

  • 本文关键字:舍入 问题 不正确 php
  • 更新时间 :
  • 英文 :


我有一个积分系统,目前,客户会获得分配的积分,每获得 500 分,他们就会获得一张 5 英镑的代金券。

目前这就是我所拥有的,如果有人在 900 分,那么输出显示他们到目前为止已经赚了 10 英镑,这是不正确的。我怎样才能四舍五入,所以它只显示 5 英镑,然后当他们获得超过 1000 分时,它会显示 10 英镑等。

<?php if($total >= 500) {
$voucher_count = $total / 500;
$voucher_rounded = round($voucher_count, 0) . "<br />";
$voucher_total = $voucher_rounded * 5; ?>
<p class="earnings-to-date">You've earned £<?php echo $voucher_total; ?> so far</p>
<?php } ?>

floor — 向下舍入分数
https://www.php.net/manual/en/function.floor.php


$total = 900;
if($total >= 500) {
$voucher_count = $total / 500;
$voucher_rounded = floor($voucher_count);
$voucher_total = $voucher_rounded * 5; 
echo $voucher_total; // Output: 5
}

只需使用模运算符 (%( 在除以 500 之前过滤掉额外的 400(或任何它(:

$total = 900;
if($total >= 500) {
$voucher_count = ($total - $total % 500) / 500;
$voucher_total = $voucher_count * 5;
echo $voucher_total;
}

输出:

5

取模运算符按指定数字计算除法的余数。 在这种情况下:

($total - $total % 500) / 500;

计算出余数($total % 500 = 400(,从$total中减去它,然后除以500

只需使用floor

$voucher_total = round(floor($total/500)) * 5;

最新更新