Ok so I am trying to turn my hit counter to round thousands to a single digit too display 3 thousand hits as 3K for example, like the Facebook Share and Twitter Tweet Button
a bit better than the post of Yuki
if ($value > 999 && $value <= 999999) {
$result = floor($value / 1000) . ' K';
} elseif ($value > 999999) {
$result = floor($value / 1000000) . ' M';
} else {
$result = $value;
}
function shortNumber($num)
{
$units = ['', 'K', 'M', 'B', 'T'];
for ($i = 0; $num >= 1000; $i++) {
$num /= 1000;
}
return round($num, 1) . $units[$i];
}
I adapted this one from a function created to display bytes in human readable form by bashy here:
https://laracasts.com/discuss/channels/laravel/human-readable-file-size-and-time
function print_number_count($number) {
$units = array( '', 'K', 'M', 'B');
$power = $number > 0 ? floor(log($number, 1000)) : 0;
if($power > 0)
return @number_format($number / pow(1000, $power), 2, ',', ' ').' '.$units[$power];
else
return @number_format($number / pow(1000, $power), 0, '', '');
}
if ($postresultscount > 999999) {
$postresultscount = floor($postresultscount / 1000000) . ' M';
}
elseif ($postresultscount > 999) {
$postresultscount = floor($postresultscount / 1000) . ' K';
}
echo $postresultscount;
Rounding up, not accounting for any abbreviations above 'k' or thousands, showing one decimal place.
function numToKs($number) {
if ($number >= 1000) {
return number_format(($number / 1000), 1) . 'k';
} else {
return $number;
}
}
numToKs(1) = 1
numToKs(111) = 111
numToKs(999) = 999
numToKs(1000) = "1.0k"
numToKs(1499) = "1.5k"
numToKs(1500) = "1.5k"
numToKs(1501) = "1.5k"
numToKs(1550) = "1.6k"
numToKs(11501) = "11.5k"
numToKs(1000000000) = "1,000,000.0k"
numToKs(1234567890) = "1,234,567.9k"
This questuion have the same goal as this question in here Shorten long numbers to K/M/B?
Reference: https://gist.github.com/RadGH/84edff0cc81e6326029c
Try this code:
function number_format_short( $n, $precision = 1 ) {
if ($n < 900) {
// 0 - 900
$n_format = number_format($n, $precision);
$suffix = '';
} else if ($n < 900000) {
// 0.9k-850k
$n_format = number_format($n / 1000, $precision);
$suffix = 'K';
} else if ($n < 900000000) {
// 0.9m-850m
$n_format = number_format($n / 1000000, $precision);
$suffix = 'M';
} else if ($n < 900000000000) {
// 0.9b-850b
$n_format = number_format($n / 1000000000, $precision);
$suffix = 'B';
} else {
// 0.9t+
$n_format = number_format($n / 1000000000000, $precision);
$suffix = 'T';
}
// Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
// Intentionally does not affect partials, eg "1.50" -> "1.50"
if ( $precision > 0 ) {
$dotzero = '.' . str_repeat( '0', $precision );
$n_format = str_replace( $dotzero, '', $n_format );
}
return $n_format . $suffix;
}
The code above create a function to convert the numbers. To use this function later just call it like in the code below:
// Example Usage:
number_format_short(7201); // Output: 7.2k