How can i copy a float value to an array of characters in c? For example the float variable x = 1.234 is copied to an array of char to become {‘ 1’ , ‘.’ , ‘2’ , ‘3’ , ‘4’}
 
    
    - 3,586
- 1
- 18
- 26
- 
                    Converting it or copying it in a new array of character – Mohamed Ahmed Nov 29 '19 at 06:02
- 
                    Use `sprintf(arr,"%f",x)`, with a large enough `arr`. – goodvibration Nov 29 '19 at 06:06
- 
                    Real simple: [sprintf(buff, %f", 1.234)](https://linux.die.net/man/3/sprintf) – paulsm4 Nov 29 '19 at 06:07
- 
                    `"%f"` results in `"0.000000"` or `"-0.000000"` for about half of all possible `double`. Do not use that to preserve information about the `double`. – chux - Reinstate Monica Nov 29 '19 at 09:08
3 Answers
Better to use snprintf over sprintf, it address many risk of buffer overflow, when the developer underestimate the required size, or the input is not fully validated.
   int status = snprintf(arr, sizeof(arr), "%.3f", val) ;
   ... Check overflow if needed ...
   if ( status >= sizeof(arr) ) {
       .. Overflow
   }
printf, like few other functions in the original stdio (gets, vsprintf) rely on the programmer to create large enough buffers.
 
    
    - 13,723
- 1
- 10
- 37
You can convert your float number to string by using sprintf() function, such as:
char fnum_str[num]; // num is an integer number which large enough
int slen = sprintf(fnum_str,"%f",fnum); // fnum is your float number
Now, your number is converted to char array in a separate characteristic fnum_str. And you can access to the value by using fnum_str[i].
 
    
    - 122
- 4
If you want to preserve all the information of a double into a string,
Use a wide enough string and s*printf() with the %a, %e  or %g format specifiers.  These use textual floating point representation.  Do not use "%f" (textual fixed point) which is uninformative with small values and too verbose with large ones.
#include <float.h>
//                    -       hex digits         .   p   -  expo \0
#define DBL_HEX_SIZE (1 + (DBL_MANT_DIG + 3)/4 + 1 + 1 + 1 + 8 + 1)
char s[DBL_HEX_SIZE * 2];  // No need to be stingy on buffer sizes.
snprintf(s, sizeof s, "%a", some_double);
or in decimal
#include <float.h>
//                    - digit .   dec digits            e   -  expo \0
#define DBL_DEC_SIZE (1 + 1 + 1 + (DBL_DECIMAL_DIG-1) + 1 + 1 + 8 + 1)
char s[DBL_DEC_SIZE * 2];  // No need to be stingy on buffer sizes.
snprintf(s, sizeof s, "%.*e", DBL_DECIMAL_DIG-1, some_double);
Details in Printf width specifier to maintain precision of floating-point value
 
    
    - 143,097
- 13
- 135
- 256
