Numbers To Words

This algorithm converts decimal numbers to its English word representation.



									/*****Please include following header files*****/
// stdint.h
// math.h
/***********************************************/

char* AppendString(const char* str1, const char* str2) {
	int str1Len = strlen(str1);
	int str2Len = strlen(str2);
	int strLen = str1Len + str2Len + 1;
	char* str = malloc(strLen);

	for (int i = 0; i < str1Len; i++)
		str[i] = str1[i];

	for (int i = 0; i < str2Len; i++)
		str[(str1Len + i)] = str2[i];

	str[strLen - 1] = '\0';

	return str;
}

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

	if (num >= 1000)
	{
		int powersLength = 7;
		for (int i = powersLength - 1; i >= 0; i--)
		{
			uint64_t power = (uint64_t)pow(1000, i);
			uint64_t count = (num - (num % power)) / power;

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

	if (num >= 100)
	{
		uint64_t count = (num - (num % 100)) / 100;
		words = AppendString(AppendString(words, NumbersToWords(count)), " hundred");
		num -= count * 100;
	}

	if (num >= 20 && num < 100)
	{
		uint64_t count = (num - (num % 10)) / 10;
		words = AppendString(AppendString(words, " "), tens[count]);
		num -= count * 10;
	}

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

	if (num > 0 && num < 10)
	{
		words = AppendString(AppendString(words, " "), singles[num]);
	}

	return words;
}
								


Example

									uint64_t data = 5478775544879599;
char* value = NumbersToWords(data);
								


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