Converting number abbreviations (5.2k, 1.7m, etc) into valid integers with PHP(使用 PHP 将数字缩写(5.2k、1.7m 等)转换为有效整数)
问题描述
我有一个数据库,其中有一列包含用速记"书写的各种数字,例如:
I have a database with a column containing a variety of numbers written in "shorthand", for example:
5k 换 5,000
86.6k 换 86,600
4,100,000 为 4.1m
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 等)转换为有效整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 PHP 将数字缩写(5.2k、1.7m 等)转换为有效整数
基础教程推荐
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01