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

后端 未结 6 1014
执笔经年
执笔经年 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: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.

提交回复
热议问题