Convert Number into Sort Number Format In PHP (Eg: 1.2K, 15.10M, 20B etc)
There are two ways to convert numbers into short number format in PHP:
To convert a number into short number format using the number_format() function, you can use the following code:
PHP
$number = 123456789;
$shortNumber = number_format($number, 0, and#39;.and#39;, and#39;and#39;);
echo $shortNumber; // Output: 123.45M
andnbsp;
content_copy
This will convert the number 123456789 to the short number format 123.45M, where M stands for million.
PHP
function shortNumber($number) {
$abbreviations = [
and#39;Kand#39; = 1000,
and#39;Mand#39; = 1000000,
and#39;Band#39; = 1000000000,
and#39;Tand#39; = 1000000000000,
];
foreach ($abbreviations as $abbreviation = $value) {
if ($number = $value) {
$number = round($number / $value, 1) . $abbreviation;
break;
}
}
return $number;
}
andnbsp;
content_copy
To use the shortNumber() function, you can use the following code:
PHP
$number = 123456789;
echo shortNumber($number); // Output: 123.45M
content_copy
This will convert the number 123456789 to the short number format 123.45M.
Which method you choose to use to convert numbers into short number format depends on your specific needs. If you need a simple and straightforward solution, then you can use the number_format() function. If you need more control over the formatting of the short number format, then you can use a custom function.