Skip to content

Instantly share code, notes, and snippets.

@clarkeash
Last active December 19, 2015 13:18
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 clarkeash/5960958 to your computer and use it in GitHub Desktop.
Save clarkeash/5960958 to your computer and use it in GitHub Desktop.
Function for rounding any number to the value of a specified base. e.g. If using base 2 (1,2,4,8,16,32,64,128....) the 17 would round up to 32.
<?php
function roundToBase($value, $base = 2)
{
$result = log($value, $base);
$result = ceil($result);
$result = pow($base, $result);
return $result;
}
//e.g. roundToBase(17); // returns 32
// supports rounding down
function roundToBase($value, $base = 2, $down = false)
{
$result = log($value, $base);
$result = $down ? floor($result) : ceil($result);
$result = pow($base, $result);
return $result;
}
//e.g. roundToBase(17, 2, true); // returns 16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment