PHP Number Tips - Part 10: In order to print a number as one or more literal words, you can use PEAR's Numbers_Words class such as:
<?php
//include Numbers_Words class
include "Numbers/Words.php";
//create object
$nw = new Numbers_Words();
//print numbers in words
//result: "190000000 in words is one hundred ninety million."
echo "190000000 in words is " . $nw->toWords(190000000) . ".\n";
//result: "637 in words is six hundred thirty-seven."
echo "637 in words is " . $nw->toWords(637) . ".\n";
// result: "-8730 in words is minus eight thousand seven hundred ↵
thirty."
echo "-8730 in words is " . $nw->toWords(-8730) . ".";
?>
The PEAR Numbers_Words class is designed specifically for the purpose of spelling out a number as one or more words. The class' toWords( ) method accepts a positive or negative integer and outputs the corresponding string.You are not limited to English-language either, the Number_Words class can translate your number into a variety of different languages such as French, Hungarian, Spanish, Russian, Polish, and German.
Here is the listing:
<?php
//include Numbers_Words class
include "Numbers/Words.php";
//create object
$nw = new Numbers_Words();
//print numbers in words in different languages
//French - result: "78 in French is soixante-dix-huit."
echo "78 in French is " . $nw->toWords(78, 'fr') . ".\n";
//Spanish - result: "499 in Spanish is cuatrocientos noventa
y nueve." echo "499 in Spanish is " . $nw->toWords(499, 'es') . ".\n";
//German - result: "-1850000 in German is minus en million
//otte hundrede halvtreds tusinde."
echo "-1850000 in German is " . $nw->toWords(-1850000, 'dk') . ".";
?>
Note that the toWords( ) method does not support decimal values. To convert decimal values and fractions, consider the toCurrency( ) method instead.