user1823053
user1823053

Reputation: 69

PHP code to round decimals up

I am using

$p1 = 66.97;

$price1  = $row['Value']*$p1;
$price1 = number_format($price1, 2, '.', '');

To do a simple calculation and then show the price to 2 decimal places. this works fine. I would like to round the result up to the nearest .05. So 18.93 would be 18.95, 19.57 would be 19.60 etc. Any ideas on this - I am struggling. Thanks.

Upvotes: 0

Views: 103

Answers (5)

Adam Zielinski
Adam Zielinski

Reputation: 2874

You may do something like:

$price = ceil($p1*20)/20;

You need to round up to 0.05; ceil normally rounds up to 1; so you need to multiply your number by 20 (1/0.05 = 20) to allow ceil do what you want, and then divide the number you came up with;

Be aware of float arithmetics, your result might really be something like 12.949999999999999999999 instead of 12.95; so you should convert it to string with sprintf('%.2f', $price) or number_format as in your example

Upvotes: 1

Marty McVry
Marty McVry

Reputation: 2856

Use following code:

// First, multiply by 100
$price1 = $price1 * 100;
// Then, check if remainder of division by 5 is more than zero
if (($price1 % 5) > 0) {
    // If so, substract remainder and add 5
    $price1 = $price1 - ($price1 % 5) + 5;
}
// Then, divide by 100 again
$price1 = $price1 / 100;

Upvotes: 0

user684202
user684202

Reputation:

$price = ceil($price1 * 20) / 20;

Upvotes: 0

OBV
OBV

Reputation: 1259

Try:

function roundUpToAny($n,$x=5) {
    return round(($n+$x/2)/$x)*$x;
}

i.e.:

echo '52 rounded to the nearest 5 is ' . roundUpToAny(52,5) . '<br />';
// returns '52 rounded to the nearest 5 is 55'

Upvotes: 0

AbdullahC
AbdullahC

Reputation: 6730

Multiply your answer by 100, then do a modulo division by 5. If the remainder is less than 3, subtract the remainder, else add (5 - remainder). Next, divide by 100 to get to the final result.

Upvotes: 0

Related Questions