Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rounding Numbers To The Nearest Half

Status
Not open for further replies.

P3rL

Programmer
Mar 28, 2001
6
AU
I would like to find out how i can round numbers to the nearest next half.

example: if i have 4.23 i would like to round it off to 4.5.

I have looked in other posts and I have only seen how to round off to the nearest full number.

I need this in a rating script which will rate things out of 10 or out of 5.

Thank you n advance.
 
You can get to the nearest tenth, by using sprintf.

$num = sprintf("%.1f", $num);
 
This sounds like a great challenge. What IS the best generic algorith for rounding to the nearest, or nearest NEXT half, quarter, etc?

Here's the best I can come up with on short notice: add .5 and subtract the modulus (remainder) .5:
Code:
$rounded = $amt + .5;
$rounded = $amt - ($amt % .5);
This would round any fraction from .1 to .5 up to .5, and any fraction from .6 to .9 to 1.0. It's not fully tested, but I think it will work.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top