Jump to content

[SOLVED] Rounding an Integer


pacchiee

Recommended Posts

Hello,

 

I want to round off an integer to end with 5 or 0 with PHP. For example:

 

21.4 should be rounded to 20

23.8 should be rounded to 25

26.4 should be rounded to 25

28.1 should be rounded to 30

 

and so on..

 

Please help. Thanks in Advance.

Link to comment
Share on other sites

<?php
function roundnum ($num, $nearest)
{
   $ret = 0;
   $mod = $num % $nearest;

   if ($mod >= 0)
     $ret = ( $mod > ( $nearest / 2)) ? $num + ( $nearest - $mod) : $num - $mod;
    else
     $ret = ( $mod > (-$nearest / 2)) ? $num - $mod : $num + ( -$nearest - $mod);
    return $ret;
}

echo roundnum (1234, 15);  // round to the nearest 15
echo roundnum (1234, 5); // round to the nearest 5
?>

 

http://www.markblah.com/2008/05/11/php-round-number-to-nearest-x/

Link to comment
Share on other sites

Hello nbarone,

 

Thanks. That function rounds an integer to the nearest specified SINGLE number. But I want to round an integer to its nearest 5 or 10 BOTH.

 

Sorry, I guess I don't quite understand what you're trying to accomplish, this function rounds to the nearest 5.

Link to comment
Share on other sites

Maybe this is what you were looking for....it takes decimal into account...prolly not the most efficient way, but it works:

 

<?php
function roundnum ($num, $nearest)
{
   $ret = 0;
   $mod = $num % $nearest;

   if ($mod >= 0)
     $ret = ( $mod > ( $nearest / 2)) ? $num + ( $nearest - $mod) : $num - $mod;
    else
     $ret = ( $mod > (-$nearest / 2)) ? $num - $mod : $num + ( -$nearest - $mod);

 $dec_check = explode(".",$ret);
 if($dec_check[1]){
 	$tenth = $dec_check[1];
	if($tenth > 4){
		$ret = $ret+$nearest;
	}
}
    return floor($ret);
}

echo roundnum (17.5, 5); // = 20
echo roundnum (17.4, 5); // = 15
?>

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.