使用PHP将数字缩写(5.2k,1.7m等)转换为有效整数 [英] Converting number abbreviations (5.2k, 1.7m, etc) into valid integers with PHP

查看:477
本文介绍了使用PHP将数字缩写(5.2k,1.7m等)转换为有效整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库,其中包含以速记编写的各种数字的列,例如:

I have a database with a column containing a variety of numbers written in "shorthand", for example:

5k for 5,000

86.6 k为86,600

4.1m为4,100,000

1.2b为1,200,000,000

5k for 5,000
86.6k for 86,600
4.1m for 4,100,000
1.2b for 1,200,000,000

我想用这些做一些计算PHP前端的数字,但我需要将它们转换为有效的整数才能这样做。我怎么能用PHP做到这一点?

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?

推荐答案

类似的东西:

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.
}

这篇关于使用PHP将数字缩写(5.2k,1.7m等)转换为有效整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆