# convert float to string

• 12-13-2002
vthokienj
convert float to string
I have a float variable that i want to get the length of.
I assume i must convert this to a string first but do not know how to do so. I tried using "sprintf(b,"%f",a)" but it would round off, and i need to preserve the exact length of the string.

for example:

float f1;
f1 = 10.1234;
char string[10];

i would need to somehow return that the length of f1 is 7 (assuming decimal is counted).

so i would need to convert f1 to "10.1234" and then just take the length of that, but f1 could not be converted to "10.1234000"

thanks for any help.
• 12-13-2002
Xaviar Khan
Vthokienj,

_fvct should take care of what you are looking for. Correct me if i'm wrong but this might help some (at worst)

Code:

```/* FCVT.C: This program converts the constant  * 3.1415926535 to a string and sets the pointer  * *buffer to point to that string.  */ #include <stdlib.h> #include <stdio.h> void main( void ) {   int  decimal, sign;   char *buffer;   double source = 3.1415926535;   buffer = _fcvt( source, 7, &decimal, &sign );   printf( "source: %2.10f  buffer: '%s'  decimal: %d  sign: %d\n",             source, buffer, decimal, sign ); }```
hth, :eek:
X
• 12-14-2002
vthokienj
thanks, this is a good idea but it just won't help me for what i need this function to do. the key for me is preserving the length.

i won't know how long my float var is, lets say it is 3.1415
and i put in a width of 10 to the fcvt function. well, it is going to
give me extra characters that i do not need.

if i have 3.1415, i need to get a string "3.1415" or '31415",
but not "3.1415000" / "3141500" or "3.142" / "3142"
• 12-14-2002
Eibro
The power of stringstreams...
Code:

```#include <iostream> #include <sstream> int main () {   using std::stringstream;   using std::cout;     double val;   stringstream ss;     ss.precision(10); ss << "3.14159";     ss >> val;   cout << val*2 << std::endl;     return 0; }```
If you're still running into rounding it's no fault of the stringstream; you're simply seeing the limitiations of a float. Remember, it's only an approximation.