# Re: [PHP] number to word converter

```Here is a slightly more readable number-to-English converter.  It will deal
with negative numbers and recognizes zero; it's table-driven, so it
shouldn't be too hard to convert to other languages.

It will convert anything in +/- 10^30.  This should be pretty comprehensive;
if not, extend the triplets table (and email me to explain what on Earth
you're doing with it!! ;-)

<?php

// Hugh Bothwell  [EMAIL PROTECTED]
// August 31 2001
// Number-to-word converter

\$ones = array(
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
);

\$tens = array(
"",
"",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
);

\$triplets = array(
"",
" thousand",
" million",
" billion",
" trillion",
" quintillion",
" sextillion",
" septillion",
" octillion",
" nonillion"
);

// recursive fn, converts three digits per pass
function convertTri(\$num, \$tri) {
global \$ones, \$tens, \$triplets;

// chunk the number, ...rxyy
\$r = (int) (\$num / 1000);
\$x = (\$num / 100) % 10;
\$y = \$num % 100;

// init the output string
\$str = "";

// do hundreds
if (\$x > 0)
\$str = \$ones[\$x] . " hundred";

// do ones and tens
if (\$y < 20)
\$str .= \$ones[\$y];
else
\$str .= \$tens[(int) (\$y / 10)] . \$ones[\$y % 10];

// add triplet modifier only if there
// is some output to be modified...
if (\$str != "")
\$str .= \$triplets[\$tri];

// continue recursing?
if (\$r > 0)
return convertTri(\$r, \$tri+1).\$str;
else
return \$str;
}

// returns the number as an anglicized string
function convertNum(\$num) {
\$num = (int) \$num;    // make sure it's an integer

if (\$num < 0)
return "negative".convertTri(-\$num, 0);

if (\$num == 0)
return "zero";

return convertTri(\$num, 0);
}

?>

and a test fn I wrote,

<?php
function randThousand() {
return mt_rand(0,999);
}

// Returns an integer in -10^9 .. 10^9
// with log distribution
function makeLogRand() {
\$sign = mt_rand(0,1)*2 - 1;
\$val = randThousand() * 1000000
+ randThousand() * 1000
+ randThousand();
\$scale = mt_rand(-9,0);

return \$sign * (int) (\$val * pow(10.0, \$scale));
}

// example of usage
for (\$i = 0; \$i < 20; \$i++) {
\$num = makeLogRand();
echo "<br>\$num: ".convertNum(\$num);
}
?>

Usage is simple:
convertNum(integer) returns a string, the value in English.

Hope this helps.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

```