Skip to content

Instantly share code, notes, and snippets.

@vjandrea
Created November 3, 2015 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vjandrea/adc4553abc38e97bf249 to your computer and use it in GitHub Desktop.
Save vjandrea/adc4553abc38e97bf249 to your computer and use it in GitHub Desktop.
Round to nearest defined cents
/*
* 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