Created
November 6, 2021 18:41
-
-
Save Taosif7/f9f3b258045e85427ad923618265a188 to your computer and use it in GitHub Desktop.
A functon to round a float number to particular float multiple.
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
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
echo roundToPrecisionMultiple(0.126, 0.12,
true
, 2); // prints 0.12echo roundToPrecisionMultiple(0.126, 0.12,
false
, 2); // prints 0.24