-2

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’}

Nipun Thennakoon
  • 3,586
  • 1
  • 18
  • 26

3 Answers3

1

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.

dash-o
  • 13,723
  • 1
  • 10
  • 37
1

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].

thangpx1706
  • 122
  • 4
-1

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

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256