Last active
July 4, 2021 14:18
-
-
Save mohammadhzp/908f7646aff9bfa7a8d68090e948734b to your computer and use it in GitHub Desktop.
php compact_number_format keep decimals as needed
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
<?php | |
function compact_number_format(float $num , int $decimals = 2 , ?string $decimal_separator = '.' , ?string $thousands_separator = ','): string { | |
$r = number_format($num, $decimals, $decimal_separator, $thousands_separator); | |
if ($decimals === 0) { | |
return $r; | |
} | |
return rtrim(rtrim($r, '0'), $decimal_separator); | |
} | |
# Please note that default value for the second argument in number_format() is 0 while in compact_number_format() is 2 | |
# echo compact_number_format("10.00", 2); // 10 | |
# echo compact_number_format("10.10", 2); // 10.1 | |
# echo compact_number_format("10.12", 2); // 10.12 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment