How to Round to the Nearest 5 Cents (Nickel) With PHP

rounding with php

I was working on a pricing calculator in PHP and I needed to round the total to the nearest five cents, since my country got rid of pennies some years ago.

For example:

$2.23 should get rounded to $2.25

$2.21 should round to $2.20

$2.28 should round to $2.30

and so on…

Oddly enough, I didn’t find a whole lot of answers online explaining how to solve this seemingly simple problem.

So I decided to post my solution here in case someone comes across the same problem.

First we store the cost in the variable:

$cost = 27.2345567;

Then we pass the cost divided by 0.05 into the round function and multiply it by 0.05. This gives us our rounded value which we can store in a variable we’ll nameround_num.

$round_num = round($cost / 0.05) * 0.05;

That will round whatever number you assign to the cost variable to the nearest 5 cents.

This won’t display zero values, so 2.20 will be displayed as 2.2 and 2.00 will be displayed a 2.

To fix this, and make our numbers display consistently, we can use PHP’s number_format function like so:

number_format($round_num, 2);

The number_format function takes two arguments separated by a comma. The first argument is the number we want to format, which is our rounded number. The second argument is the number of decimal places we want to show. In this case we say 2 because that is the convention for pricing.

Here is the whole script, where we echo out the final cost at the end:

$cost = 27.2345567;
$round_num = round($cost / 0.05) * 0.05;
echo number_format($round_num, 2);

I am sure there is a more elegant way to do this, and by all means, post it in the comments.

But it works, and is pretty simple. So if you are like me and trying to solve this problem, maybe you will find this useful.

Leave a Reply

Your email address will not be published. Required fields are marked *