在PHP中,将整数四舍五入到最接近的5的倍数



搜索一个函数,将数字四舍五入到的最近倍数

22 -> 20
23 -> 25
40 -> 40
46 -> 45
48 -> 50

等等

尝试了这个总是返回更高的值:

5 * ceil($n / 5);

使用round()而不是ceil()

5 * round($n / 5);

ceil()将一个浮点数四舍五入到其序列中的下一个整数。round()将使用标准舍入规则四舍五入到最接近的整数。

回到数学,因为四舍五入适用于小数,乘以5,除以10,然后四舍五进。再次乘以5可以得到你想要的。(其他答案也适用,只是从不同的角度来看)

function round_5($in)
{
return round(($in*2)/10)*5;
}
echo round_5(48);

看看这是否有助于

在帮助一家加拿大公司制作POS时,遇到了这个问题,提出了这个解决方案,希望它能帮助到别人。(加拿大在2012年撤掉了这笔钱)。还包括进行含税定价,只需将"1"作为第二个参数。

//calculate price and tax
function calctax($amt,$tax_included = NULL){
$taxa = 'tax rate 1 here';
$taxb = 'tax rate 2 here';
$taxc = ($taxa + $taxb) + 1;
if(is_null($tax_included)){
$p = $amt;
}else{
$p = number_format(round($amt / $taxc,2),2);
} 
$ta = round($p * $taxa,2);
$tb = round($p * $taxb,2);
$sp = number_format(round($p+($ta + $tb),2),2);
$tp = number_format(round(($sp*2)/10,2)*5,2);
$ret = array($ta,$tb,$tp);
return $ret;
}

最新更新