1

I have one android application in which I am using PHP API for get data from server. This is quote application and in which I have function of counting likes and shares of quotes. I am converting that count in k style number like 1K for 1000 etc with below function.

function Get_convert_to($value)
{
    if ($value > 999 && $value <= 999999) {
        $result = floor($value / 1000) . ' K';
    } elseif ($value > 999999) {
        $result = floor($value / 1000000) . ' M';
    } else {
        $result = $value;
    }

    return $result;
}

Now my issue is its returning 1K for even 1400....I want 1.4K for 1400. How can I do that?

Thanks

localheinz
  • 9,179
  • 2
  • 33
  • 44
Priya
  • 1,602
  • 4
  • 22
  • 37
  • Remove `floor()`...That function rounds the value downwards to the nearest integer value, in your example to 1... – Usagi Miyamoto Sep 03 '17 at 05:34
  • Possible duplicate of [Format bytes to kilobytes, megabytes, gigabytes](https://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes) – localheinz Sep 03 '17 at 06:54

3 Answers3

1

To get value like 1.4 (one decimal) use parameter to control decimal

<?php 
function Get_convert_to($value){


    if ($value > 1000) {
        $result = round(($value / 1000),1) . ' K';
    } elseif ($value > 999999) {
        $result = round(($value / 1000000),1) . ' M';
    } else {
        $result = $value;
    }


    return $result;
}

echo Get_convert_to(1400);
?>

Output:

1.4K

Jigar Shah
  • 6,143
  • 2
  • 28
  • 41
0

You simply need to remove floor because it will give you nearest lower value after division. ec 1.4/1.2 will become 1

function Get_convert_to($value){


    if ($value > 999 && $value <= 999999) {
    $result = ($value / 1000) . ' K';
} elseif ($value > 999999) {
    $result = ($value / 1000000) . ' M';
} else {
    $result = $value;
}


    return $result;
    }
B. Desai
  • 16,414
  • 5
  • 26
  • 47
  • hi ! in this case its giving me 1.025 K for 1025. I need only 1K for it. if 1050 then it will return 1.1 K etc – Priya Sep 03 '17 at 05:44
0

If you want control the number of decimal you can use number format on division

  $result  =  number_format($value / 1000, 1, '.', '') . ' K'; ;
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107