Created
October 6, 2010 22:03
-
-
Save joshtronic/614183 to your computer and use it in GitHub Desktop.
Round with Precision
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: