I have a blog where I show the number of visits of each article I publish and some articles have gained many visits and the number of visits is sometimes very long and it ruins the responsiveness of the web and that is why I have chosen to shorten the number of visits: e.g. 2330 visits = 2.3K visits and that way it looks much better and prettier for me.
Result that throws me
It turns out that this gives me a wrong and very false result: p, eg: 523 Visits = 52K Visits Bone says that there are 52 thousand visits when in reality there are only 523 visits and those that have, for example, 2,821 Visits say 2.8K Visits Which it means that there is a problem in the function that I will show you later
result i want
What I want is that if my article has 523 visits, simply and simply say that you have 523 visits. But if this one has 2,425 Visits, let it say 2.4K and that's it.
function i use
// Abreviatura de la cantidad de visitas
function abreView($visita) {
$visitantes = number_format($visita, 0, '.', ',');
$posicion_coma = strpos($visitantes, ",");
return substr($visitantes, 0, ($posicion_coma + 2)) . "K";
}
This is the function that I am using to achieve my goal but it seems something is wrong and I don't know how to correct it, I hope you can help me please.
You can implement this function:
Source: This Stackoverflow answer on the question: Shorten long numbers to K/M/B?
As you can see, the scope is longer, reaching up to trillions... you can remove what doesn't interest you, but who knows, one day your site could have trillions of visits :-).
If you were receiving values with thousand separators, you can clean the data by adding a
str_replace
to the beginning of the function, thus avoiding problems of badly formatted numbers, etc.: