2012-10-16 16 views
6

的5最接近的倍數搜索功能RO輪編號,以5回合整數在PHP

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

等最接近的倍數。

試過這個總是返回高值:

5 * ceil($n/5); 
+0

嘗試模運算符:'$ n - ($ n%5);'通常這些情況通常是最好的。 – Mahn

回答

20

使用round(),而不是ceil()

5 * round($n/5); 

ceil()將一個浮點數循環到下一個整數的順序。 round()將使用標準舍入規則舍入到最接近的整數。

+0

thx男人,這很容易:) – Chris

+1

'''round()'''返回一個不是整數的浮點數。 ''(int)5 * round($ n/5);'''可以更好。 – trante

+0

@trante它會舍入到一個整數,但它仍然是'float'類型。 – alex

0

回到數學,因爲回合使用小數,乘以5併除以10,然後四捨五入。再乘以5得到你想要的。 (Other答案工程,以及,看它只是用不同的方式)

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

echo round_5(48); 

看看這有助於

0

那麼,面對這一問題,同時幫助使一個加拿大公司的POS,想出了這個解決方案,希望它能幫助別人。 (加拿大在2012年取消了這一便士)。還包括做稅收的定價,只是通過'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; 
}