For a three-digit number (negative or positive), you just need to divide it into sections and remember that numbers less than 20 are special (in any block of a hundred). As pseudo-code (well, Python, actually but close enough to pseudo-code), we first define the lookup tables:
nums1 = ["","one","two","three","four","five","six","seven",
"eight","nine","ten","eleven","twelve","thirteen",
"fourteen","fifteen","sixteen","seventeen","eighteen",
"nineteen"]
nums2 = ["","","twenty","thirty","forty","fifty","sixty",
"seventy","eighty","ninety"]
Note that there's no onety
for numbers between ten and nineteen. As previously mentioned, numbers under twenty in each block of a hundred are treated specially.
Then we have the function which first checks the input value and handles negative numbers as a one-level recursive call. It also handles the special case of zero:
def speak (n):
if n < -999 or n > 999:
return "out of range"
if n < 0:
return "negative " + speak (-n)
if n == 0:
return "zero"
Next step is to work out the three digits in the number:
hundreds = int (n / 100)
tens = int ((n % 100) / 10)
ones = n % 10
Hundreds are simple since it's only zero through nine:
if hundreds > 0:
retstr = nums1[hundreds] + " hundred"
if tens != 0 or ones != 0:
retstr = retstr + " and "
else:
retstr = ""
The rest is simply treating values from zero to nineteen as special, otherwise we treat it as X
ty Y
(like forty two
or seventy seven
):
if tens != 0 or ones != 0:
if tens < 2:
retstr = retstr + nums1[tens*10+ones]
else:
retstr = retstr + nums2[tens]
if ones != 0:
retstr = retstr + " " + nums1[ones]
return retstr
And a quick and dirty test suite at the bottom:
for i in range (-1000, 1001):
print "%5d %s"%(i, speak (i))
produces:
-1000 out of range
-999 negative nine hundred and ninety nine
-998 negative nine hundred and ninety eight
:
-2 negative two
-1 negative one
0 zero
1 one
2 two
:
10 ten
11 eleven
12 twelve
:
998 nine hundred and ninety eight
999 nine hundred and ninety nine
1000 out of range