TUTORIALS

October 30 2010

## PHP Round Numbers By Half Tutorial

By Bill Krom

While working on an interesting contest poll / voting system for wiki-pet.com. I needed to develop a function that will round numbers to the nearest half, since the poll will allow half star voting. While seemingly simple at first glance, this is the kind of problem that may cause you some extra unneeded frustration in your hectic day.

Wiki Pet will be having a "Cutest Pet" competition in the near future, and i'm building a pretty nifty application to allow users to vote on which pets are their favorites. More on that later, but for now, i will share this short and simple function to hopefully save some of you guys some time if you ever have the need for such a thing.

This function will take a number, check it against the floor (next lowest whole number) and ceil (or ceiling, next highest whole number) and determine which end of the round to begin on. If, for instance, the number in question is 1.56 the function determines that it is indeed higher than the median (or 1.50) and will then compare it to the results of the round() function that gave us the highest whole number (2.0).

Next, it will determine which of the two numbers is closest to the original with a quick comparison (is 1.56 closest to 1.5 or 2.0).

Lastly, it will round the number to the next nearest half.

```
<?php
function roundHalf(\$num){
\$fl_num = floor(\$num);
\$rd_num = round(\$num);
// find the middle
\$mid_num = \$fl_num + 0.5;
// find the distance between the number and the floor
\$fl_dist = \$num-\$fl_num;
// find the distance between the number and the ceil
\$rd_dist = \$rd_num-\$num;
// if the number is over the middle, compare it to the round
if(\$num < \$mid_num){
(\$fl_dist > \$mid_num-\$num ? \$new_num = \$mid_num : \$new_num = \$fl_num);
}
else{
// compare it to the floor
if(\$rd_dist > \$num-\$mid_num ? \$new_num = \$mid_num : \$new_num = \$rd_num);
}
return \$new_num;
}
?>```

If you are looking to call this function, simply use:
```
<?php
\$my_new_rounded_num = roundHalf(\$your_number);
?>
```

The new number is returned from the function, so just assign it to a variable or whatever and your all set!

That's about it! I'm sure you can come up with extensions and fancy up this function to do all sorts of dorky number crunching! Feel free to leave comments and share how you used it!

## 1 comment for "PHP Round Numbers By Half Tutorial"

### HOME

Posted: 3/17/2013 - 9:10PM

it tech support

Take tours of any properties that you are interested in. Think about having a contractor that's a professional with you while you check out different properties. Make a proposal early, and open the negotiating table. Before making any commitment, be sure to carefully evaluate all counteroffers.