PHP: Round to the Nearest 0.5 (1.0, 1.5, 2.0, 2.5, etc.)

by Yang Yang on October 24, 2012

The common practice of rounding, namely the round() function in PHP, is to round to the nearest decimal point, that is, 1.0, 2.0, 3.0, etc. or, 10, 20, 30, etc. For example,

echo round(4.25, 0);		// 4
echo round(3.1415926, 2);	// 3.14
echo round(299792, -3);		// 300000

When I’m trying to aggregate all the customer ratings for a specific provider in one of my web hosting reviews community, I want to round the average rating to the nearest 0.5 (half the decimal) so that a half star would be correctly displayed.

This is more of a mathematical problem than a PHP one. After some thinking and testing, I came up with a slightly more sophisticated solution than but the round() function:

echo round(1.7 * 2) / 2;		// 1.5
echo round(2.74 * 2) / 2;		// 2.5
echo round(2.75 * 2) / 2;		// 3.0
echo round(3.1 * 2) / 2;		// 3.0

Just as easy as that.

Comments on this entry are closed.

Previous post:

Next post: