Converting number abbreviations (5.2k, 1.7m, etc) into valid integers with PHP
If this is your data format, and is consistent. you can write your own function. create a map of suffix to multiplier.. "k" => 1000, "m" => 100000
and multiply the integer value with multiplier value. Here is a sscanf based solution : http://codepad.org/FjwBbx1D
<?php
$map = array("k" => 1000,"m" => 1000000,"b" => 1000000000);
$money = "86.6k";
list($value,$suffix) = sscanf($money, "%f%s");
$final = $value*$map[$suffix];
var_dump($final);
?>
And here is a simple one liner:
<?php
$money = "86.6k";
$value = substr($money,0,-1)*pow(10,strpos("---k--m--b",substr($money,-1))) ;
var_dump($value);
?>
Something like:
switch (strtolower(substr($input, -1))) {
case 'k':
$input*=1000;
break;
// similarly for m, M, b, B.
}
Assuming your data is well-formatted. If not more check would be needed like:
if (!preg_match('/^\d+(?:\.\d+)?[mbk]$/i',$input)) {
// $input is not a valid format.
}
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.