floor value in php function

254 views Asked by At

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

3

There are 3 answers

2
Jigar Shah On BEST ANSWER

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

1
B. Desai On

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;
    }
0
ScaisEdge On

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

  $result  =  number_format($value / 1000, 1, '.', '') . ' K'; ;