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)
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!
August 7th, 2008 at 11:44 am
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)
September 23rd, 2008 at 8:10 am
wow…
Its very nice…
Excellent…
I like this code very much…
February 26th, 2009 at 11:11 pm
[...] [via] addthis_url = ‘http%3A%2F%2Fjared.simplistika.com%2Fconvert-number-to-word-spelling%2F’; addthis_title = ‘AS3+Convert+Number+to+Word+Spelling’; addthis_pub = ”; [...]
June 15th, 2010 at 11:13 pm
Thank you very much….
Really nice….
Great Work…
i used this code in my projects…