# ftoa??? Is there a direct way to convert a float to a string?

• 12-13-2002
Trauts
ftoa??? Is there a direct way to convert a float to a string?
I know how itoa works...

int x = 100;
char xstring[4];
itoa(x,xstring,10);

But I need to convert a FLOAT to a string! Can anyone help me?

double x = 100.10
char xstring[7];
ftoa(x,xstring,10);

I need it to store the decimal place, too.

Is there a header file that supports this, or does anyone have a function for it?
• 12-13-2002
Trauts
I think I just figured it out...

_ecvt Convert double to string of specified length
_fcvt Convert double to string with specified number of digits following decimal point
_gcvt Convert double number to string; store string in buffer

I should use _gcvt, right?

If so, how can I get it to work right:

value

Value to be converted

digits

Number of significant digits stored

buffer

Storage location for result

I want digits to store whatever is stored in the floating point version... if I put in 1024, will it store 1024 characters even if they don't have a value?
• 12-13-2002
Trauts
too late now oh well
• 12-13-2002
you could also look up use of stringstreams, if you dont' like to use sprintf(). Though I suspect both versions will have difficulty expressing floats or decimals that don't terminate, like pi, or one third, etc. You probably need to decide on a given approximation to the actual float to convert to a string. Once you do that, you could even create your own function, if you want to continue using itoa.

//I decided to use only use first 4 decimal places;
float fNum = 1.2345;
int wholeNum = fNum;//wouldn't hurt to cast it to avoid warning
int decimalNum = (int) ((fNum - wholeNum) * 10000);
char wholeNumStr[10];
char decNumStr[5];
char decPtStr = ".";
char numStr[17];
itoa(wholeNumStr, wholeNum);
itoa(decNumStr, decimalNum);
strcpy(numStr, wholeNumStr);
strcat(numStr, decPtStr);
strcat(numStr, decNumStr);

cout << numStr << endl;

All sorts of options for you.