How do I convert a float to a string value? For this program I\'m asking the use
ID: 3662416 • Letter: H
Question
How do I convert a float to a string value?
For this program I'm asking the user "how much allotted time they set for game play in hours" and then I go into a while loop asking them "how much time they have spent so far (type DONE PLAYING to quit)". If they type a number then that number is subtracted from the first number that they gave and they are told how much time they have left. However, if they type "DONE PLAYING" then the program exits the loop and a summary of their game time is presented.
Explanation / Answer
Converts a floating point number to string.
void ftoa(float n, char *res, int afterpoint)
{
// Extract integer part
int ipart = (int)n;
// Extract floating part
float fpart = n - (float)ipart;
// convert integer part to string
int i = intToStr(ipart, res, 0);
// check for display option after point
if (afterpoint != 0)
{
res[i] = '.'; // add dot
// Get the value of fraction part upto given no.
// of points after dot. The third parameter is needed
// to handle cases like 233.007
fpart = fpart * pow(10, afterpoint);
intToStr((int)fpart, res + i + 1, afterpoint);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.