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

后端 未结 6 967
执笔经年
执笔经年 2021-01-02 22:02

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

相关标签:
6条回答
  • 2021-01-02 22:42

    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

    0 讨论(0)
  • 2021-01-02 22:51

    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.

    0 讨论(0)
  • 2021-01-02 22:54

    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.

    0 讨论(0)
  • 2021-01-02 22:59
    $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 讨论(0)
  • 2021-01-02 23:01

    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.
    }
    
    0 讨论(0)
  • 2021-01-02 23:04

    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);
    ?>
    
    0 讨论(0)
提交回复
热议问题