Most solutions here only work for integers. This one will also work for numbers like 1.5M
or 6.83K
.
I think this function is much cleaner and more efficient
function formatAbbreviationToNumber($number) {
$abbrevs = array(12 => "T", 9 => "B", 6 => "M", 3 => "K", 0 => "");
foreach($abbrevs as $exponent => $abbrev) {
if(strtoupper(substr($number, -1)) == $abbrev) {
return substr_replace($number, "", -1) * pow(10, $exponent);
}
}
}
And the other way around:
function formatNumbertoAbbreviation($number) {
$abbrevs = array(12 => "T", 9 => "B", 6 => "M", 3 => "K", 0 => "");
foreach($abbrevs as $exponent => $abbrev) {
if(abs($number) >= pow(10, $exponent)) {
return intval($number / pow(10, $exponent)) . $abbrev;
}
}
}
It goes up to trillion, you can add higher values if you want but make sure you put them in the array from highest to lowest.