Number.php
32 lines
| 1 | <?php |
| 2 | |
| 3 | namespace IAWPSCOPED\Proper; |
| 4 | |
| 5 | /** @internal */ |
| 6 | class Number |
| 7 | { |
| 8 | /** |
| 9 | * @param int|float $number |
| 10 | * |
| 11 | * @return string |
| 12 | */ |
| 13 | public static function abbreviate($number, $round = \false) : string |
| 14 | { |
| 15 | $number = (int) $number; |
| 16 | $abbreviations = ['' => 1, 'K' => 1000, 'M' => 1000000, 'B' => 1000000000, 'T' => 1000000000000]; |
| 17 | foreach ($abbreviations as $abbreviation => $abbreviation_value) { |
| 18 | $upper_range = $abbreviation_value * 1000; |
| 19 | if ($number < $upper_range) { |
| 20 | $decimals = $number < 1000 || $round ? 0 : 1; |
| 21 | $result = $number / $abbreviation_value; |
| 22 | $result = \number_format_i18n($result, $decimals) . $abbreviation; |
| 23 | // Strip out decimals that are 0 so 1.0T becomes 1T |
| 24 | $result = \strpos($result, '.0') === \false ? $result : \str_replace('.0', '', $result); |
| 25 | return $result; |
| 26 | } |
| 27 | } |
| 28 | // Do nothing for numbers past the trillions |
| 29 | return \number_format_i18n($number, 0); |
| 30 | } |
| 31 | } |
| 32 |