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 等)转换为有效整数
基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
