### help to Convert float to string

I have an assignment that is due on monday I am stuck on this function. I have to convert my netpay which is a float to a string So if i have 356.26
it should output the sum of three hundred fifty-six and 26/100 dollars
my program function works for the sum of three hundred but after that it spits out garbage.

void convertNetPay(float netPay, char *netPayString)
{
int numHuns, numTens, numOnes;
char OnesTable[9][8]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
char ResultString[10+1];
char TensTable[9][8] = {"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
char TeensTable[9][10] ={"Eleven", "Twelve","Thirteen","fourteen","fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
float cents;

cents = netPay - int(netPay);

strcpy(netPayString,"The sum of ");

numHuns = int(netPay) / 100;

if (numHuns > 0)
{
strcat(netPayString,OnesTable[numHuns-1]);
strcat(netPayString," Hundred ");

}
int remainder = int(netPay) % 100;
/*if (remainder ==0)
{
//do sumthing
}*/

if ((remainder<=11) || (remainder>=19))
{

strcat(netPayString, TeensTable[remainder -11]);
}
else{

numTens = int(netPay) % 100 / 10;

numOnes = int(netPay) % 100 % 10;
if (numTens > 0)
{
strcat(netPayString,TensTable[numTens -1]);
strcat(netPayString," - ");
}
if (numOnes > 0)
{
strcat(netPayString,OnesTable[numOnes-1]);
strcat(netPayString," Dollars and ");
}

cents = cents + 0.005;

cents = cents * 100;
cents=int(cents);
sprintf(ResultString,"%d",cents);
strcat(netPayString,ResultString);
}

}
How about converting the float into characters, then pushing them back onto a string.
 ``12`` `````` sprintf(ResultString,"%d",cents); strcat(netPayString,ResultString);``````

ResultString was declared:
 `` `` ``char ResultString[10+1];``

And has not been modified since. It will inevitably contain junk. Perhaps this is what you meant?
 ``12345`` ``````char ResultString[11] = "cents"; //... sprintf("%d %s.", cents, ResultString); strcat(netPayString,ResultString);``````

Also, I do not see where you are translating cents to a string.
Last edited on
Topic archived. No new replies allowed.