Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting number abbreviations (5.2k, 1.7m, etc) into valid integers with PHP

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?

like image 620
MarathonStudios Avatar asked Mar 29 '11 03:03

MarathonStudios


3 Answers

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);
?>
like image 62
DhruvPathak Avatar answered Nov 06 '22 19:11

DhruvPathak


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.
}
like image 5
codaddict Avatar answered Nov 06 '22 18:11

codaddict


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.

like image 5
Gilles Lesire Avatar answered Nov 06 '22 19:11

Gilles Lesire