开发者

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

I h开发者_C百科ave 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.


There is a PHP function given on the manual's page of ini_get() (in the manual page itself -- not in the users notes), that does just that.

Quoting :

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}


Note that this function is used to show how to convert shorthand byte values to integer bytes values, and, as such, considers that 1k = 1024 ; and not 1000.


Logic to implement, iterate through all the characters, and when you find a character (not digit) just save the index. Now split that into two parts: digital value and character. Now create a function which returns the value of passed character. eg. getValueOf('M')=1000000 And then finally do this Numerical Value * getValueOf('M') That's all. Note: Your numerical values have commas in it so also do str_replace(',','',numeric value) and then convert to int


$string = '5k'; // or whatever
$suffix = strspn($string, '.0123456789');
$value = doubleval(substr($string, 0, $suffix))
if($suffix < strlen($string))
{
 switch($string[$suffix])
 {
  case 'k':
   $value *= 1000;
   break;
  case 'm':
   $value *= 1000000;
   break;
  case 'b':
   $value *= 1000000000;
   break;
 }
}
echo number_format($value);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜