How to just convert float to string in c?

FILE * fPointer;
float amount = 3.1415;
fPointer =fopen("vending.txt","w");
fprintf(fPointer ,amount);
printf("The file has been created for the first time and we added the value %f" , amount);
fclose(fPointer);

I am trying to save a floating point number in a text file, but when I try to run this code, it starts compiling errors because the fprintf function expects the second parameter to be an array of characters, since I can convert my float to a string so that I could pass it, I came from aC # background, where something like .toString () is possible, so is there something like this in c to directly output the float to a string?

+3
source share
4 answers

The second parameter is a format string followed by format arguments:

fprintf(fPointer, "%f", amount);

%fsays fprintfto write this argument ( amount) as a string representation of a floating point value.

() .

+4

sprintf(), float c .

#include <stdio.h>
int main()
{
   float f = 1.123456789;
   char c[50]; //size of the number
    sprintf(c, "%g", f);
    printf(c);
    printf("\n");
}

, .

+1

C99, - snprintf. (null), , . , , .

sprintf, .

:

int len = snprintf(null, 0, "%f", amount);
char *result = (char *)malloc(len + 1);
snprintf(result, len + 1, "%f", amount);
// do stuff with result
free(result);
+1
// OP code           v---- Format string expected here. 
// fprintf(fPointer, amount);

To print a different text for each float, use the format string "%.*e".
FLT_DECIMAL_DIG - 1- the number of digits required to print each value is floatunambiguous without unjustified accuracy.

#include <float.h>
#include <stdio.h>

fprintf(fPointer, "%.*e", FLT_DECIMAL_DIG - 1, amount);

Usage "%f"will print almost half of small ones float, such as 0.000000001fand -1.2345e-10how 0.000000or -0.000000.

Usage "%f"will print large floatas FLT_MAXwith long text like "340282346638528859811704183484516925440.000000".

+1
source

Source: https://habr.com/ru/post/1665308/


All Articles