PHP 'NumberFormatter' 'SPELLOUT' 未提供所需的英文格式

标签 php symfony numberformatter

我在代码中使用 PHP NumberFormatter 将价格值转换为文字 例如,如果是 125 卢比,那么应该是“一百二十五”而不是“一百二十五”。

我尝试过其他示例,例如检查每个数字单位值并替换单词

$numberFormatterClass = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);
echo str_replace('-', ' ', $numberFormatterClass->format($number));

期望 125 =“一百二十五”

最佳答案

当数字超过 99 时,您只能生成最后两位数字的拼写。然后你就知道在哪里插入“和”了。在代码中:

$number = 125;

$numberFormatter = new \NumberFormatter('en', \NumberFormatter::SPELLOUT);
$fullSpellout = str_replace('-', ' ', $numberFormatter->format($number));
if ($number > 100) {
   $lastTwoSpellout = str_replace('-', ' ', $numberFormatter->format(substr($number, -2)));
   $hunderdsLength = strlen($fullSpellout) - strlen($lastTwoSpellout); 
   $fullSpellout = substr($fullSpellout, 0, $hunderdsLength) . 'and ' . $lastTwoSpellout; 
}

echo $fullSpellout;

输出:

one hundred and twenty five

这当然不是唯一可能的解决方案。插入“and”的方法有很多种,如果最后两位数字总是生成两个单词,您也可以使用它来检测插入“and”的位置。

这是一个基于单词并使用数组插入“and”的版本:

$number = 125;

$numberFormatter = new \NumberFormatter('en', \NumberFormatter::SPELLOUT);
$spellout = str_replace('-', ' ', $numberFormatter->format($number));
if ($number > 100) {
   $words = explode(' ', $spellout); 
   array_splice($words, -2, 0, ['and']);
   $spellout = implode(' ', $words); 
}

echo $spellout;

关于PHP 'NumberFormatter' 'SPELLOUT' 未提供所需的英文格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57370234/

相关文章:

java - 在Java中使用HTTP post来模拟Web浏览器

php - 如何防止 jQuery post 处理程序被恶意使用?

symfony - 奏鸣曲管理包 : strange with labels

php - 在 Laravel 5.4 中找不到类 'NumberFormatter'

php - NumberFormatter 总是在 float 后面保留 2 位数字

javascript - 页面标题内的时间脚本

php - 从多表中选择语句

php - Symfony2 和 FOSUserBundle : Override Mailer

php - 使用 Doctrine Extensions Tree Nested 集获取家长中的 child 帖子

java - 将字符串转换为十六进制