Last active
April 6, 2017 09:19
-
-
Save ludo237/58a5962fb2ce9ee81f2534de07470f7f to your computer and use it in GitHub Desktop.
Round numbers in order to have something more human readable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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