Skip to content

Instantly share code, notes, and snippets.

@joshtronic
Created October 6, 2010 22:03
Show Gist options
  • Save joshtronic/614183 to your computer and use it in GitHub Desktop.
Save joshtronic/614183 to your computer and use it in GitHub Desktop.
Round with Precision
<?php
/**
* Rounds a float with direction.
*
* Since round() doesn't support an optional rounding mode until 5.3 I
* had to roll my own function to do so in the meantime.
*
* Note: Does not support negative precision.
*
* @static
* @param float $value the value to be rounded
* @param integer $precision optional decimal precision to round to
* @param string $mode optional direction to round to
* @return float potentially rounded value
*/
public static function round($value, $precision = 0, $mode = null)
{
if ($precision >= 0)
{
$offset = (int)str_pad('1', $precision + 1, '0');
$value = (string)($value * $offset);
}
switch ($mode)
{
case 'floor':
$value = floor($value);
break;
case 'ceiling':
$value = ceil($value);
break;
default:
$value = round($value);
break;
}
if ($precision >= 0)
{
$value = number_format($value / $offset, 2);
}
return $value;
}
?>
@joshtronic
Copy link
Author

line #22, if you don't cast the value as a string it becomes a float. once a float floor() may not handle as you'd except. case in point, 10.2:

var_dump(floor(10.2 * 100), floor(1020), floor((string)(10.2 * 100)));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment