Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active March 7, 2022 15:32
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 kobus1998/0ea3348a44e9806c67be36e7f8f6a06c to your computer and use it in GitHub Desktop.
Save kobus1998/0ea3348a44e9806c67be36e7f8f6a06c to your computer and use it in GitHub Desktop.
round
<?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