Rounding to the nearest half dollor (or quarter dollar)

One of my recent projects required that I round the price I was calculating to the nearest half dollar. This started out at a pain. Rounding to the floor, or to the ceiling, or normal rounding is quite easy. But I have never had to round to the nearest half dollar. (or quarter dollar) After a little bit of time thinking about it, I came up with a solution.I first thought about the algorithm needed to round to the floor or to the ceiling. This was easy, since the project is a PHP project, I simply had to use the rounding functions. Rounding to the nearest half dollar was harder because we had to come up with a way to round evenly. So here is the algorithm I used:

$rounded = round(($initial_value / .5), 0) * .5

There you have it. A very simple (and quick way) of rounding to the nearest half dollar. To be able to round to the nearest quarter dollar, tenth of a dollar or anything else you feel like rounding to, simply change the .5 to .25 (for quarter dollar) or .1 (for tenth of a dollar) depending on what is needed.

One Response to “Rounding to the nearest half dollor (or quarter dollar)”

  1. A fun discussion merits comment. In my opinion that is recommended you write more on this topic, it might be a taboo subject but generally people are isn’t to dicuss on such topics. An additional. Cheers

Leave a Reply


Switch to our mobile site