Jump to content

Need a bit of help with a rounding up function


c_shelswell

Recommended Posts

Hi i have a function that i got off the php manual site. It rounds up figures to the nearest 2 decimals for me but an odd thing happened last night. Basically i fed it 1.1 and it gave me 1.11

 

here's my code

 

function roundUp ($value, $places=2)
{
  if ($places < 0) 
  { 
   	$places = 0;
  }
  $mult = pow(10, $places);
  
  return ceil($value * $mult) / $mult;
}

 

any help would be great cheers

Hi, try use round($number,$decimals)

http://it.php.net/round

 

For example:

function roundUp ($value, $places=2)
{
  if ($places < 0) 
  { $places = 0; }
  $mult = pow(10, $places);
  
  $x=ceil($value * $mult) / $mult;
  return round($x,2);
}

Try this, it should let you round up or down depending on what you want :)

 

<?php
function rounding($no,$direction)
   {                            
   $skip=0;
   if(is_float($no) and $direction = 1)
       {
       $exploded = explode(".",$no);
       $nrr = $exploded[0]+1;    $skip=1;
       }

   if(is_float($no) and $direction = 0)
       {
       $exploded = explode(".",$no);
       $nrr = $exploded[0];        $skip=1;
       }

   if(!is_float($no) and $skip ==1) { $nrr = $nrr; } else { $nrr = floor($nrr); }

     return $nrr;
   }
   
?>

 

Use it like this:

echo rounding(1.6,0);

 

Enter the number first followed bya boolen, 1 to round up, 0 to round down. Always a nice little function to have lying around :)

Cool thanks i also just found this which seems to work too.

 

function roundUp( $value, $dec = 2 ) 
{
     $value += 0.00;
     $unit  = floor( $value * pow( 10, $dec + 1 ) ) / 10;
     $round = ceil( $unit );
     return $round / pow( 10, $dec );
}

 

i guess you could replace the ceil to floor depening on if you wanted to round up or down.

 

Cheers

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.