A conversion from integer to long form english... I could write that ;-)
[Editorial note: A more complete sample is available through article: http://weblogs.asp.net/justin_rogers/articles/151757.aspx]
I find little conversion functions to be the most interesting type of programming you can spend your time on. You wind up exercising so many areas of programming expertise to make the algorithms short, complete, bug free, and as fast as possible. While this next algorithm fits a couple of those, I have to admit I'm quite tired and I only spent about 20 minutes working the solution. It would be interesting to extend the algorithm to work with decimals, possibly units of measure, etc...
using System;
public class NumberToEnglish {
private static string[] onesMapping =
new string[] {
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
private static string[] tensMapping =
new string[] {
"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
private static string[] groupMapping =
new string[] {
"Hundred", "Thousand", "Million", "Billion", "Trillion"
};
private static void Main(string[] args) {
Console.WriteLine(EnglishFromNumber(long.Parse(args[0])));
}
private static string EnglishFromNumber(int number) {
return EnglishFromNumber((long) number);
}
private static string EnglishFromNumber(long number) {
if ( number == 0 ) {
return onesMapping[number];
}
string sign = "Positive";
if ( number < 0 ) {
sign = "Negative";
number = Math.Abs(number);
}
string retVal = null;
int group = 0;
while(number > 0) {
int numberToProcess = (int) (number % 1000);
number = number / 1000;
string groupDescription = ProcessGroup(numberToProcess);
if ( groupDescription != null ) {
if ( group > 0 ) {
retVal = groupMapping[group] + " " + retVal;
}
retVal = groupDescription + " " + retVal;
}
group++;
}
return sign + " " + retVal;
}
private static string ProcessGroup(int number) {
int tens = number % 100;
int hundreds = number / 100;
string retVal = null;
if ( hundreds > 0 ) {
retVal = onesMapping[hundreds] + " " + groupMapping[0];
}
if ( tens > 0 ) {
if ( tens < 20 ) {
retVal += ((retVal != null) ? " " : "") + onesMapping[tens];
} else {
int ones = tens % 10;
tens = (tens / 10) - 2; // 20's offset
retVal += ((retVal != null) ? " " : "") + tensMapping[tens];
if ( ones > 0 ) {
retVal += ((retVal != null) ? " " : "") + onesMapping[ones];
}
}
}
return retVal;
}
}