Convert numbers to words

Numbers are great, sure, but sometimes you need to spell them out … and if you think the possibility for that to happen is slim, invoices and checks for example need to have the ammount in both numbers and letters (in most countries).

That’s why a script to convert numbers to words (to spell numbers) can come in handy.


function number_to_words ($x)
{
     global $nwords;
     if(!is_numeric($x))
     {
         $w = '#';
     }else if(fmod($x, 1) != 0)
     {
         $w = '#';
     }else{
         if($x < 0)
         {
             $w = 'minus ';
             $x = -$x;
         }else{
             $w = '';
         }
         if($x < 21)
         {
             $w .= $nwords[$x];
         }else if($x < 100)
         {
             $w .= $nwords[10 * floor($x/10)];
             $r = fmod($x, 10);
             if($r > 0)
             {
                 $w .= ' '. $nwords[$r];
             }
         } else if($x < 1000)
         {
		
             	$w .= $nwords[floor($x/100)] .' hundred';
             $r = fmod($x, 100);
             if($r > 0)
             {
                 $w .= ' '. number_to_words($r);
             }
         } else if($x < 1000000)
         {
         	$w .= number_to_words(floor($x/1000)) .' thousand';
             $r = fmod($x, 1000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $w .= ' ';
                 }
                 $w .= number_to_words($r);
             }
         } else {
             $w .= number_to_words(floor($x/1000000)) .' million';
             $r = fmod($x, 1000000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $word .= ' ';
                 }
                 $w .= number_to_words($r);
             }
         }
     }
     return $w;
}

Download: numbers-words.zip (1 KB)

Demo

The zip file contains the source code to convert numbers to words in both English and Romanian (you never knew when you need 'em).

So ... enjoy!

2 thoughts on “Convert numbers to words”

  1. I noticed a couple bugs you may or may not want to fix.

    Some spelling errors:
    1. ‘eightteen’ should be ‘eighteen’
    2. ‘fourty’ should be ‘forty’
    3. ‘eigthy’ should be ‘eighty’

    A grammatical error:
    1. Two digit numbers greater than 20 and not ending in zero should be separated by a hyphen, not a space. i.e. ‘twenty one’ should be ‘twenty-one’, ‘eighty nine’ should be ‘eighty-nine’, etc. (http://en.wikipedia.org/wiki/List_of_numbers#Small_numbers)

Leave a Reply

Your email address will not be published. Required fields are marked *

Security question: * Time limit is exhausted. Please reload the CAPTCHA.