Created
November 3, 2015 15:34
-
-
Save vjandrea/adc4553abc38e97bf249 to your computer and use it in GitHub Desktop.
Round to nearest defined cents
This file contains 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
/* | |
* Rounds to the nearest 5 cents | |
* Modified from @dancameron's version | |
* For $mode values see http://php.net/manual/en/function.round.php | |
* | |
* @param float $amount | |
* @param int $mode (default = PHP_ROUND_HALF_UP) | |
* @return float | |
*/ | |
function round_money($amount = 0.0, $mode = PHP_ROUND_HALF_UP) { | |
// check if $mode is valid | |
if (!in_array($mode, [PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD]) { | |
$mode = PHP_ROUND_HALF_UP; | |
} | |
$whole = $amount * 100; | |
$rounded_whole = round(($whole * 2) / 10, $mode) * $cents; | |
$rounded = $rounded_whole / 100; | |
return $rounded; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment