Skip to content

Instantly share code, notes, and snippets.

@ludo237
Last active April 6, 2017 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ludo237/58a5962fb2ce9ee81f2534de07470f7f to your computer and use it in GitHub Desktop.
Save ludo237/58a5962fb2ce9ee81f2534de07470f7f to your computer and use it in GitHub Desktop.
Round numbers in order to have something more human readable
<?php
/**
* Round a number into an human readable number
*
* The idea is to converts numbers like 999,999 into something like 0.9M or 999.99K
* using the scientific notation.
*
* @param $number
*
* @return string
*
*/
function roundForHumans($number)
{
$number = round($number);
$numberToArray = explode(',', number_format($number));
$result = $numberToArray[0] . ((int)$numberToArray[1][0] !== 0 ? '.' . $numberToArray[1][0] : '');
$result .= ['k', 'm', 'b', 't'][(count($numberToArray) - 1) - 1];
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment