Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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