Created
March 27, 2023 19:04
-
-
Save ldommer/0a6c16181cae90b5f8d216254f242ad4 to your computer and use it in GitHub Desktop.
Round a number as string with dependent decimals in PHP.
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 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