Question

I have a database with a column containing values in numeric format , for example:

5,000 for 5k 

86,600 for 86.6k

4,100,000 for 4.1m

while displaying in the browser it should display like 5k for 5000 ,86.6k for 86,600,etc..I need the code in php. If there is any built-in function to do this please mention it .

Was it helpful?

Solution

If you have them as numbers, you can use this function directly.

function formatValue($size, $precision = 1)
{
    static $suffixes = array('', 'k', 'm');
    $base = log($size) / log(1000);

    return round(pow(1000, $base - floor($base)), $precision) . $suffixes[floor($base)];
}

If you don't have them as numbers, use PHP: unformat money

For you particular case you may use little dirty hack, but I don't recommend it if you have more special cases.

function formatValue($size, $precision = 1)
{
    static $suffixes = array('', 'k', 'm');
    $base = log($size) / log(1000);

    if ($base >= 5/3 && $base < 2) {
        return round(pow(1000, $base - floor($base)) / 100, $precision) . 'lakh';
    }

    return round(pow(1000, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top