Try this. It should be fairly simple to convert the remaining numbers to text.
Code:
#include <stdio.h>
#include <string.h>
/*************************** FUNCTION PROTOTYPES *******************************/
void NumToWord(double num);
void ParseNum(char *strnum, int i, int level);
void PrintIt(char *str, int level);
/*******************************************************************************/
int main(void)
{
double num;
// test data
num = 12345678901.23;
NumToWord(num);
printf("\n");
// test data
num = 123456.78;
NumToWord(num);
printf("\n");
//test data
num = 1234567890123.45;
NumToWord(num);
return 0;
}
void
NumToWord(double num)
{
int i;
int level = 0; // used to determine what string to print in "PrintIt"
char cents[3];
char strnum[21]; // working variable; make sure variable is large enough!
sprintf(strnum, "%.2f", num); // make sure the double has only 2 decimal places
i = strlen(strnum);
do // find the period, if it exists
{
i--;
}
while (i && strnum[i] != '.');
if (i) // found a period, parse out the "cents" amount
{
strncpy(cents, strnum+i+1, 2);
cents[2] = '\0';
strnum[i] = '\0';
}
ParseNum(strnum, i, level); // start parsing the whole amount
PrintIt(cents, 6);
}
void
PrintIt(char *str, int level)
{
switch (level)
{
case 1:
printf(" %s Dollars ", str);
break;
case 2:
printf(" %s Thousand ", str);
break;
case 3:
printf(" %s Million ", str);
break;
case 4:
printf(" %s Billion ", str);
break;
case 5:
printf(" %s Trillion ", str);
break;
case 6:
printf(" and %s cents", str);
break;
}
}
void
ParseNum(char *strnum, int i, int level)
{
char str[4];
if (i >= 3)
{
str[0] = strnum[i-3];
str[1] = strnum[i-2];
str[2] = strnum[i-1];
str[3] = '\0';
strnum[i-3] = '\0';
i -= 3;
level++;
if (i)
ParseNum(strnum, i, level); // not done, recursive call to parse again
PrintIt(str, level);
}
else if (i == 2)
{
str[0] = strnum[i-2];
str[1] = strnum[i-1];
str[2] = '\0';
level++;
PrintIt(str, level);
}
else if (i == 1)
{
str[0] = strnum[i-1];
str[1] = '\0';
level++;
PrintIt(str, level);
}
}