In web design sometimes itโs neccesary to keep things short, so large numbers have to be trimmed for display. The following simple code will format any number > to 1000 to its 1K version and will limit decimals to 2 digits.
$shares = $this->page->shares;
$shares2 = $shares / 1000;
if ($shares < 1000) {
echo โ$shares’;
}
else {
echo number_format($shares2, 2);
echo โk’;
}
With this simple code, a number preserves its format if itโs lower than 1000 (i.e. 856). But a number like 1599 becomes 1.59K. The code after โelseโ echoes just 2 digits and prints โkโ after the number.
This code is only good for numbers between 1000 and 999999, so it has to be expanded for millions or more, It can be done by adding another conditional for higher numbers.