I have the following code that rounds my amounts to the nearest Dollar:
switch ($amazonResult['SalesRank']) {
case ($amazonResult['SalesRank'] < 1 || trim($amazonResult['SalesRank'])===''|| !isset($amazonResult['SalesRank']) || $amazonResult['SalesRank']=== null):
$Price=((float) $lowestAmazonPrice) * 0.05;
$payPrice = round($Price, 0); //to round the price up or down to the nearest $
break;
case ($amazonResult['SalesRank'] > 0 && $amazonResult['SalesRank'] <= 15000):
$Price=((float) $lowestAmazonPrice) * 0.20;
$payPrice = round($Price, 0); //to round the price up or down to the nearest $
break;
I understand that if I use round($Price, 2); that I will have 2 decimal places, but is there a way to round to the nearest 50 cents?
Multiply by 2, round to 0 in the digit above you want to round to .5 (round to the ones decimal place in your case), divide by 2.
That will give you rounding to the nearest .5, add on a 0 and you have rounding to the nearest .50.
If you want the nearest .25 do the same but multiply and divide by 4.
Some simple mathematics should do the trick. Instead of rounding to the nearest 50 cents, round double the $price
to the nearest dollar, then half it.
$payprice = round($Price * 2, 0)/2;
From the manual: echo round(1.95583, 2); // 1.96
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
val
The value to round
precision
The optional number of decimal digits to round to.
mode
One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD.
Just change to : echo round(1.54*2, 0)/2; // 1.5
function roundnum($num, $nearest){
return round($num / $nearest) * $nearest;
}
eg:
$num = 50.55;
$nearest = .50;
echo roundnum($num, $nearest);
returns
50.50
This can be used to round to anything, 5cents, 25cents, etc...
credit to ninjured : http://forums.devshed.com/php-development-5/round-to-the-nearest-5-cents-537959.html
divide number by nearest, do the ceil, then multiply by nearest to reduce the significant digits.
function rndnum($num, $nearest){
return ceil($num / $nearest) * $nearest;
}
Ex.
echo rndnum(95.5,10) returns 100
echo rndnum(94.5,1) returns 95
Notice that if you use floor instead of round, you need an extra round because of the internal precision of the float numbers.
function roundnum($num, $nearest){
return floor(round($num / $nearest)) * $nearest;
}
$num = 16.65;
$nearest = .05;
echo roundnum($num, $nearest);
Otherwise it will return 16.60 instead of 16.65