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.

<?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.

Tags: ,

Leave a comment