![]() |
Converts a number into a short version, eg: 1000 -> 1k |
Example:
PHP
<?php
// Converts a number into a short version, eg: 1000 -> 1k
// Based on: http://stackoverflow.com/a/4371114
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;
}
/*
Example Usage:
number_format_short(7201); // Output: 7.2k
Demo:
echo '<table>';
for($d = 0; $d < 16; $d++ ) {
$n = intval("09" . str_repeat( "0", $d ));
$n = $n / 10;
echo number_format_short($n) .'<br>'; // 0.9
$n = intval("1" . str_repeat( "0", $d ));
echo number_format_short($n) .'<br>'; // 1.0
$n = intval("11" . str_repeat( "0", $d ));;
$n = $n / 10;
echo number_format_short($n) .'<br>'; // 1.1
}
echo '</table>';
?>
How to add Short Number Formatter for PHP (1000 to 1k; 1m; 1b; 1t) | PHP Number Tutorial |
Full Code of Short Number Formatter | PHP Number Tutorial |
Read Full: | PHP Number Tutorial |
Category: | Web Tutorial |
Sub Category: | PHP Number Tutorial |
Uploaded: | 1 year ago |
Uploaded by: | Admin |
Views: | 88 |