Skip to content

Instantly share code, notes, and snippets.

@ldommer
Created March 27, 2023 19:04
Show Gist options
  • Select an option

  • Save ldommer/0a6c16181cae90b5f8d216254f242ad4 to your computer and use it in GitHub Desktop.

Select an option

Save ldommer/0a6c16181cae90b5f8d216254f242ad4 to your computer and use it in GitHub Desktop.
Round a number as string with dependent decimals in PHP.
<?php
function roundNumber(float $number, int $precision = 2, string $separator = '.'): float
{
if (str_contains($number, '.')) {
$parts = explode($separator, (string)$number);
$decimals = str_split($parts[1]);
$length = count($decimals);
$counter = $length - $precision;
if ($length > $precision) {
for ($i = $counter; $i > 0; $i--) {
if ((int)$decimals[$length - 1] > 4) {
(int)$decimals[$length - 2]++;
}
unset($decimals[$length - 1]);
$length--;
}
}
return (float)implode($separator, [$parts[0], implode('', $decimals)]);
}
return $number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment