Convert any big number into short number format using PHP like 5000 to 5K, 5M, 5B etc.

In this tutorial i am going to share simple php code snippet to convert any big number into short number format. which help you to display short version of any big number as you have seen on many website they display 1000 = 1K, If you have same requirement then you can just copy below function and use in your project.


Convert any big number into short number format

<?php
function ShortNumberFormat( $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;
}
?>
 
</php>

Call the function and pass you big number and you can also set decimal places for short number format.

echo ShortNumberFormat(1010); // OUTPUT: 1K
echo ShortNumberFormat(1010,2); // OUTPUT: 1.01K

See Live Demo

DEMO



Posted in: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.