Last active
March 7, 2022 15:32
-
-
Save kobus1998/0ea3348a44e9806c67be36e7f8f6a06c to your computer and use it in GitHub Desktop.
round
This file contains hidden or 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
<?php | |
function round($f, $to = 2) | |
{ | |
list($major, $decimals) = explode('.', $f); | |
$digits = str_split($decimals); | |
$digits = array_reverse($digits); | |
$count = count($digits) - 1; | |
$iMaxKey = $count - $to + 1; | |
for ($i = 0; $i < $count; $i++) { | |
if ($iMaxKey == $i) { | |
break; | |
} | |
if ($digits[$i] >= 5) { | |
$digits[$i + 1]++; | |
} | |
unset($digits[$i]); | |
} | |
$digits = array_reverse($digits); | |
if ($to == 0) { | |
return reset($digits) >= 5 ? $major+1 : $major; | |
} | |
return "{$major}." . implode($digits); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment