Round integer with nearest multiple of 5 in PHP

Search for the ro function around numbers to the nearest multiple of 5

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

etc.

Tried this, which always returns a higher value:

 5 * ceil($n / 5); 
+6
source share
3 answers

Use round() instead of ceil() .

 5 * round($n / 5); 

ceil() rounds the floating-point number to the next integer. round() rounded to the nearest integer using standard rounding rules.

+20
source

Back to the math, since round work with decimals, multiply by 5 and divide by 10, and then round. Multiply by 5 to get what you want. ( Other answers , just a different look at it)

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

See if it helps

0
source

Well, having encountered this problem, helping to make POS for a Canadian company, came up with this solution, I hope this helps someone. (Canada removed a penny in 2012). Also includes taxes, including prices, just pass “1” as the second 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; } 
0
source

Source: https://habr.com/ru/post/927833/


All Articles