I have a small function that converts a number say 1000 to 1k.
<?php
/**
* /Converts a number into a short version, eg: 1000 -1k.
*
* @param int $number The number
* @param int $precision The precision
*
* @return string The formated number
*/
function short_number_format($number, $precision = 1)
{
$lookup = [
1 => '',
1000 => 'K',
1000000 => 'M',
1000000000 => 'B',
1000000000000 => 'T',
];
$result = '';
foreach ($lookup as $boundary => $postfix) {
if ($number < 900 * $boundary) {
$result = number_format($number / $boundary, $precision).$postfix;
break;
}
}
//if we didnt get the result which is most likely to happen
// for larger numbers (rarely) , return the plain number
return $result ?: number_format($number, $precision);
}
Some senior dev told me the code terribly runs slow because of the loop. How true is that?