I have a database with a column containing a variety of numbers written in "shorthand", for example:
5k for 5,000
86.6k for 86,600
4.1m for 4,100,000
1.2b for 1,200,000,000
I'd like to do some calculations with these numbers for a PHP frontend, but I need to convert them into valid integers in order to do so. How could I do this 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With