简体   繁体   English

在PHP中舍入整数到最接近的5的倍数

[英]Round integer to nearest multiple of 5 in PHP

Searching for a function ro round numbers to the nearest multiple of 5 搜索函数ro将数字舍入到最接近的5的倍数

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

and so on. 等等。

Tried this which always returns the higher value: 试过这总是返回更高的价值:

5 * ceil($n / 5);

Use round() instead of ceil() . 使用round()而不是ceil()

5 * round($n / 5);

ceil() rounds a floating point number up to its next integer in sequence. ceil()按顺序将浮点数ceil()到下一个整数。 round() will round to the nearest integer using standard rounding rules. round()将使用标准舍入规则舍入到最接近的整数。

Back to maths, since round works with decimals, multiply by 5 and divide by 10 and then round, it. 回到数学,因为舍入使用小数,乘以5除以10然后舍入,它。 Multiply by 5 again to get what u want. 再乘以5得到你想要的东西。 ( Other answer works as well, just a different way of looking at it) 其他答案也有效,只是以不同的方式看待它)

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

echo round_5(48);

See if this helps 看看这是否有帮助

Well, facing this issue while helping make an POS for a Canadian company, came up with this solution, hope it helps someone. 好吧,在为一家加拿大公司制作POS时面对这个问题,提出了这个解决方案,希望它可以帮到某个人。 (Canada removed the penny in 2012). (加拿大在2012年取消了一分钱)。 Also includes for doing tax included pricing, just pass '1' as second argh. 还包括进行含税定价,只是通过'1'作为第二个argh。

    //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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM