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
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;

}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.