Number Abbreviation in PHP
- 289.7K Unique Visitors
- 384.2K Page Views
- 99.1K Bot Views
When dealing with large numbers, you'll want to abbreviate them to fit in a smaller space and increase comprehension at a glance.
This script includes a function that processes any number 1,000 and larger. You can add any number of decimal places into the abbreviation.
Source Code
PHP
<?php
// Function from https://www.albinoblacksheep.com/webmaster/number-abbreviation
function format_number_precise($num, $precision=1) {
if ($num < 1000) {
return $num;
}
$units = array('', 'K', 'M', 'B', 'T');
$log = (int)(log($num, 1000));
return round($num / pow(1000, $log), $precision) . $units[$log];
}
?>
<?php
$filePath = $_SERVER['DOCUMENT_ROOT'] . '/file-with-number.txt';
if (file_exists($filePath)) {
$numberViews = file_get_contents($filePath);
echo format_number_precise($numberViews, 1) . ""; // Outputs: 1.5K
} else {
echo "File does not exist.";
}
?>