2

I Am using PHP NumberFormatter in my code to convert price value in words for example, if it is rupees 125 then it should be 'One hundred and twenty five' instead of 'one hundred twenty five'.

I have tried the other examples like checking each digit unit value and replace the words

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

expecting for 125 = "One hundred and twenty five"

Nikhil Gowda
  • 417
  • 5
  • 16

2 Answers2

3

When the number is above 99 you can generate the spellout for the last two digits only. You then know where to insert the "and". In code:

$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;

This outputs:

one hundred and twenty five

This is certainly not the only possible solution. There are many ways to insert the "and", and if the last two digits always generate two words you could also use that to detect where to insert the "and".

Here's a version based on words and using an array to insert the '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;
KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • be sure that you have installed package php-intl (php5-intl,php7.0-intl and etc.) – Tsvetomir Tsvetkov Aug 06 '19 at 07:26
  • 1
    I don't think this works. NumberFormatter does not use minus signs, but utf8 soft hyphen between numbers. So `str_replace('-', '', $str);` will not work. Instead doing `preg_replace('~\x{00AD}~u', '', $str);` works. Not sure if this is an issue with locale. – Moritz Ringler Jan 28 '21 at 15:01
0

You can use this:

$numberFormatterClass = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);

// add this line
$numberFormatterClass->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%spellout-numbering-verbose");

echo str_replace('-', ' ', $numberFormatterClass->format($number));

output: one hundred and twenty five

See this comment in this answer: PHP: Express Number in Words

Alcalyn
  • 1,531
  • 14
  • 25