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

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

提交回复
热议问题