Numbers To Words

This algorithm converts decimal numbers to its English word representation.



									public static string NumbersToWords(ulong num)
{
	StringBuilder words = new StringBuilder();
	string[] singles = new string[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
	string[] teens = new string[] { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
	string[] tens = new string[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninty" };
	string[] powers = new string[] { "", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion" };

	if (num >= 1000)
	{
		for (int i = powers.Length - 1; i >= 0; i--)
		{
			ulong power = (ulong)Math.Pow(1000, i);
			ulong count = (num - (num % power)) / power;

			if (num > power)
			{
				words.Append(NumbersToWords(count) + " " + powers[i]);
				num -= count * power;
			}
		}
	}

	if (num >= 100)
	{
		ulong count = (num - (num % 100)) / 100;
		words.Append(NumbersToWords(count) + " hundred");
		num -= count * 100;
	}

	if (num >= 20 && num < 100)
	{
		ulong count = (num - (num % 10)) / 10;
		words.Append(" " + tens[count]);
		num -= count * 10;
	}

	if (num >= 10 && num < 20)
	{
		words.Append(" " + teens[num - 10]);
		num = 0;
	}

	if (num > 0 && num < 10)
	{
		words.Append(" " + singles[num]);
	}

	return words.ToString();
}
								


Example

									ulong data = 5478775544879599;
string value = NumbersToWords(data).Trim();
								


Output

									five quadrillion four hundred seventy eight trillion seven hundred seventy five billion five hundred forty four million eight hundred seventy nine thousand five hundred ninty nine