Jump to content

Round to nearest 0 or 5


johnsmith153

Recommended Posts

I need to take a time and convert so it is rounded up or down to the nearest 0 or 5.

 

function roundMe ($time, $upDown) {

  if($upDown==1) {
     //round up
  } else {
     //round down
  }

  return $x;

}

echo roundMe("16:22", 1); // returns 16:25
echo roundMe("16:22", 0); // returns 16:20
echo roundMe("16:25", 1); // returns 16:25
echo roundMe("16:59", 1); // returns 17:00
echo roundMe("16:59", 0); // returns 16:55

Link to comment
https://forums.phpfreaks.com/topic/211190-round-to-nearest-0-or-5/
Share on other sites

If $time is always a string with a colon in it:

 

function roundMe ($time, $upDown) {
  list($hrs, $mins) = explode(':', $time);

  // Is it already on a 5-minute boundary?
  if (($mins % 5) == 0) return $time;

  if($upDown==1) {
     //round up
    $mins += 5 - ($mins % 5);
  } else {
     //round down
    $mins -= ($mins % 5);
  }

  if ($mins < 10) $mins = '0' . $mins;

  return $hrs . ':' . $mins;

}

Oops! Sorry, I forgot about the hours thing.  Looks like you fingured it out though.

 

By the way, click the "Solved" button at the bottom of the post so others can see that there is a solution to the question.  It's almost at the bottom of the page.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.