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 等)转换为有效整数


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Laravel 仓库 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01