Jump to content


Photo

Rounding to the nearest .5


  • Please log in to reply
4 replies to this topic

#1 phpvolution

phpvolution
  • Members
  • PipPip
  • Member
  • 13 posts

Posted 14 June 2006 - 08:23 AM

I've looked for a while to find an answer on this and haven't come up with anything.

I have a number, say 6.7

I want it to round in increments of .5, and to the nearest. I'm trying to make a php version of the formula I used in excel, which was the floor() function.. only in excel I used: =FLOOR(SUM(I4:L4)/4,0.5)

So 6.7 should be 6.5, 6.75 should still be 6.5, 6.76 should be 7. And so on.
Any ideas on how I can do this?

#2 joquius

joquius
  • Members
  • PipPipPip
  • Advanced Member
  • 319 posts

Posted 14 June 2006 - 10:10 AM

sure take
$string * 2
and then round to nearest and then divide it by 2
ex:
6.4 * 2 = 12.8 = 13 = 6.5
6.23 = 12.46 = 12 = 6
z..z..z..z..z..z..z..z..

#3 phpvolution

phpvolution
  • Members
  • PipPip
  • Member
  • 13 posts

Posted 14 June 2006 - 10:24 AM

Thanks, my brain doesn't seem to be functioning!

$x = floor($x*2)/2;
voila.

#4 joquius

joquius
  • Members
  • PipPipPip
  • Advanced Member
  • 319 posts

Posted 14 June 2006 - 10:32 AM

you will need to use round if you want 7 for 6.8 and not 6.5
z..z..z..z..z..z..z..z..

#5 phpvolution

phpvolution
  • Members
  • PipPip
  • Member
  • 13 posts

Posted 14 June 2006 - 10:34 PM

Thanks for pointing that out,
6.75 was being rounded up instead of down also, so I went with an If statement to handle that.

if(substr($x,1) > .75) {
$y = round($x*2)/2;
}
else {
$y = floor($x*2)/2;
}

Seems to work. thanks.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users