Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding to nearest 50 cents

Tags:

php

rounding

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?

like image 567
Jim Avatar asked Jul 27 '12 17:07

Jim


People also ask

Do you round up or down at 50 cents?

To round, drop amounts under 50 cents and increase amounts from 50 to 99 cents to the next dollar. For example, $1.39 becomes $1 and $2.50 becomes $3.

How do you write 50 cents in Excel?

Using the CHAR Function You can use the Excel CHAR function to insert the cent symbol in a cell in Excel. To do this, enter =CHAR(162) in a cell and press enter.

How do you round to the nearest half dollar?

When rounding to the nearest half, round the fraction to whichever half the fraction is closest to on the number line. If a fraction is equally close to two different halves, round the fraction up.

How do you round to the nearest 5 cents in Excel?

How to do easily do 5-cent cash rounding in Excel? Just use the regular Excel ROUND function but divide the amount by 5 before rounding to 2 decimal places then multiply the resulting amount by 5 after the rounding.


3 Answers

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.

like image 160
Scott Chamberlain Avatar answered Sep 26 '22 18:09

Scott Chamberlain


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

like image 37
Naitik Shah Avatar answered Sep 22 '22 18:09

Naitik Shah


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;
like image 36
Palladium Avatar answered Sep 22 '22 18:09

Palladium