跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

PHP怎么将数字转英文单词_PHP中NumberFormatter类使用【教程】

NumberFormatter 初始化失败:找不到 intl 扩展 PHP 报
Class 'NumberFormatter' not found
或
Call to undefined class NumberFormatter
,基本就是
intl
扩展没启用。这不是代码问题,是环境配置缺失。 Linux(如 Ubuntu):运行
sudo apt install php-intl
,然后重启 Web 服务(
sudo systemctl restart apache2
或
sudo systemctl restart php-fpm
) macOS(Homebrew + PHP):执行
brew install icu4c && pecl install intl
,并在
php.ini
中确认有
extension=intl
Windows:打开
php.ini
,取消注释
;extension=php_intl.dll
,确保
icu*.dll
文件在 PHP 的
ext
目录且系统 PATH 可达 用
php -m | grep intl
或
phpinfo()
页面确认
intl
已加载,否则后续所有调用都会直接报错 NumberFormatter::SPELLOUT 不支持中文 locale 的数字读法 想用
zh_CN
或
zh_Hans
让
NumberFormatter
输出“一百二十三”,会发现它只返回空字符串或原始数字——因为
NumberFormatter::SPELLOUT
在 ICU 数据中**仅对英文、法文、德文等少数语言提供拼写规则,中文没有内置实现**。 可用的 locale 示例:
en_US
、
fr_FR
、
de_DE
、
es_ES
;
zh_CN
、
ja_JP
、
ko_KR
均不支持
SPELLOUT
验证方式:
var_dump((new NumberFormatter('zh_CN', NumberFormatter::SPELLOUT))->format(123));
→ 返回
false
或空串 若硬要中文读法,得自己写映射逻辑(个/十/百/千/万/亿)或引入第三方库,
NumberFormatter
在这里帮不上忙 小数、负数、大数的 format 行为差异
NumberFormatter::SPELLOUT
对输入数字很敏感:小数会被转成“point zero five”,负号变成“minus”,超大整数可能截断或 fallback 到科学计数法拼写。 PHP 8.5.5 PHP 8.5.5 是 PHP 8.5 分支的维护更新版本。该版本延续了“小步快跑”的迭代逻辑,通过深度错误修复、底层性能微调以及安全加固,旨在为开发者提供一个更健壮、更高效的运行环境。该版本严格遵守语义化版本规范,不包含破坏性变更。 下载 小数:输入
3.14
→ 输出
"three point one four"
(不是 "three and fourteen hundredths") 负数:输入
-42
→ 输出
"minus forty-two"
,无法去掉 "minus" 大数:输入
1234567890
(十位以上)在某些 ICU 版本中可能返回空或异常,建议先
is_int($n) && $n < 1000000
做范围校验 locale 影响读法细节:例如
en_GB
中
100
是 "one hundred",而
en_US
一样;但
1234
在英式英语中倾向 "one thousand two hundred and thirty-four",美式常省略 "and" —— 实际取决于底层 ICU 版本,不可强依赖 替代方案:不用 intl 扩展也能凑合用 如果服务器不能装
intl
,又只要英文基础拼写(0–999),可以手写一个轻量函数,避开扩展依赖和 locale 陷阱。 立即学习 “ PHP免费学习笔记(深入) ”; 核心思路:把数字拆成百位、十位、个位,查表映射(
['zero','one',..., 'ninety-nine']
) 注意边界:0 单独处理;11–19 是特殊词(eleven, twelve…);20 以上十位+个位要加连字符(
twenty-one
) 示例片段:
function numToWords(int $n): string {
if ($n === 0) return 'zero';
$ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
$teens = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen'];
$tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty'];
// …(完整逻辑略)
return $result;
}
缺点明显:不支持小数、负数、百万以上;但胜在可控、无依赖、调试方便 ICU 版本差异比想象中大,同一段
NumberFormatter
代码在 PHP 7.4 和 8.2 上可能输出不同结果,尤其是带空格、连字符或大小写。真要上生产,务必在目标环境实测几个关键数字,别只信本地开发机。

相关文章