Answers for "Shorten long numbers to K/M/B?"

PHP
1

Shorten long numbers to K/M/B?

<?php
function convert(int $number)
{
    if ($number >= 1E9) {
        return round($number / 1E9, 2).'b';
    } else if ($number >= 1E6) {
        return round($number / 1E6, 2).'m';
    } else if ($number >= 1E3) {
        return round($number / 1E3, 2).'k';
    }
    return $number;
}

echo convert(1000000000).PHP_EOL; // 1b
echo convert(1000000).PHP_EOL;    // 1m
echo convert(1200).PHP_EOL;       // 1.2k
echo convert(1234).PHP_EOL;       // 1.23k
echo convert(100).PHP_EOL;        // 100
Posted by: Guest on August-28-2020

Code answers related to "Shorten long numbers to K/M/B?"

Browse Popular Code Answers by Language