How to convert number to words in PHP

For example you need to convert a particular amount number into a word, let say

55892 – “fifty five thousand eight hundred ninety two”

To achieve this we can use below given code:

<?php
$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”,
” quadrillion”,
” 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);
}
// 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
echo “-5564 : “.convertNum(-5564).”<br>”;
echo “55892 : “.convertNum(55892);
?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s