Round to the Nearest Half in Php

Sometimes, you want to round a number, but you want the nearest half instead of a full number. For example, if you have an average rating, and you want to display a star graphic representing the number of stars. In the interest of simplicity, you would like to show only full or half stars (3.5 stars instead of 3.43 stars). Here is a very simple example of how to do this in php.

$average = 3.43;
$round_to = 0.5; // you can change this to any increment you like
$rounded = round($average / $round_to) * $round_to;

The variable “$rounded” is now set to 3.5.

This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>