Skip to content

Instantly share code, notes, and snippets.

@Taosif7
Created November 6, 2021 18:41
Show Gist options
  • Save Taosif7/f9f3b258045e85427ad923618265a188 to your computer and use it in GitHub Desktop.
Save Taosif7/f9f3b258045e85427ad923618265a188 to your computer and use it in GitHub Desktop.
A functon to round a float number to particular float multiple.
/**
* Function to round a number to a precision multiple
*
* @param float $number original number
* @param float $pointMultiple the point multiple to which it needs to be rounded
* @param bool $roundDown whether to round up or down
* @param int $precision precision for rounding
* @return float rounded float number
*/
function roundToPrecisionMultiple(float $number,
float $pointMultiple = 0.25,
bool $roundDown = true,
int $precision = 2): float
{
$lowerBound = floor($number);
$roundedNum = $lowerBound;
while ($roundedNum <= round($number, $precision)) {
$roundedNum += $pointMultiple;
}
return $roundDown ? ($roundedNum - $pointMultiple) : $roundedNum;
}
@Taosif7
Copy link
Author

Taosif7 commented Nov 6, 2021

echo roundToPrecisionMultiple(0.126, 0.12, true, 2); // prints 0.12
echo roundToPrecisionMultiple(0.126, 0.12, false, 2); // prints 0.24

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment