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

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

     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:

    
    

提交回复
热议问题