Function: Convert Numbers to Words

August 8, 2010 | By greg | Posted in PHP Advanced

This little, recursive, script is to convert a number, an integer, to words. It has an upper limit of 999,999,999 but you can expand or reduce it from there.

Put the function in your include file and try it out.

/*
 *  Function:    number_to_words
 *  Description:  recursive numerics to words function
 *  Converts a given integer (in range [0..1T-1], inclusive) into
 *  alphabetical format ("one", "two", etc.)
 *  @int
 *  @return string
 */ 

function number_to_words($number)
{
    if (($number < 0) || ($number > 999999999))
    {
       throw new Exception("Number is out of range");
    }

    $Gn = floor($number / 1000000);  /* Millions (giga) */
    $number -= $Gn * 1000000;
    $kn = floor($number / 1000);     /* Thousands (kilo) */
    $number -= $kn * 1000;
    $Hn = floor($number / 100);      /* Hundreds (hecto) */
    $number -= $Hn * 100;
    $Dn = floor($number / 10);       /* Tens (deca) */
    $n = $number % 10;               /* Ones */ 

    $result = ""; 

    if ($Gn)
    {  $result .= number_to_words($Gn) . " Million";  } 

    if ($kn)
    {  $result .= (empty($result) ? "" : " ") . number_to_words($kn) . " Thousand"; } 

    if ($Hn)
    {  $result .= (empty($result) ? "" : " ") . number_to_words($Hn) . " Hundred";  } 

    $ones = array("", "One", "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
        "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen",
        "Nineteen");
    $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",
        "Seventy", "Eigthy", "Ninety"); 

    if ($Dn || $n)
    {
       if (!empty($result))
       {  $result .= " and ";
       } 

       if ($Dn < 2)
       {  $result .= $ones[$Dn * 10 + $n];
       }
       else
       {  $result .= $tens[$Dn];
          if ($n)
          {  $result .= "-" . $ones[$n];
          }
       }
    }

    if (empty($result))
    {  $result = "zero"; } 

    return $result;
} 

For an example, I could use it in my captcha prompt below. Recently, I have had

$Rnum1 = rand(20, 155) ;
$Rnum2 = rand( 1, 5) ; # the ranges are inclusive.
$_SESSION['captcha_correct_answer'] = $Rnum1 - $Rnum2 ;
...
Starting with < ?php echo $Rnum1; ?> give away < ?php echo $Rnum2; ?>
to get < input type="text" name="captcha" maxlength="40" size="4" />
(the answer, to stop automated spam)

What we need to add is these 2 statements right after the "$_SESSION[..." line:

$Rnum1 = number_to_words($Rnum1) ;
$Rnum2 = number_to_words($Rnum2) ;

Leave a Reply

Website url (required)

Comment / Question