11
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 float number to a text file, but when I try to run this code it triggers a compiling error because the function fprintf expects the second parameter to be an array of characters.

So how can I convert my float to a string so I can pass it? I have a C# background where something like .toString() is possible, is there anything like that in C to directly convert a float to a string?

0

4 Answers 4

15

If you can use C99 standard, then the best way is to use snprintf function. On first call you can pass it a zero-length (null) buffer and it will then return the length required to convert the floating-point value into a string. Then allocate the required memory according to what it returned and then convert safely.

This addresses the problem with sprintf that were discussed here.

Example:

int len = snprintf(NULL, 0, "%f", amount);
char *result = malloc(len + 1);
snprintf(result, len + 1, "%f", amount);
// do stuff with result
free(result);
8

The second parameter is the format string after which the format arguments follow:

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

%f tells fprintf to write this argument (amount) as string representation of the float value.

A list of possible format specifiers can (for example) be found here.

1
  • 1
    Suggest "%e" instead of "%f". The latter will print nearly half of all float as "0.000000' or "-0.000000'. Commented Dec 30, 2016 at 12:37
3

By using sprintf() we can convert from float to string in C. For better understanding see the below code:

#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
  • You should avoid to use float in the way shown here. The compiler reads 1.123456789 into a double which is then converted into float by rounding. A float is only guaranteed to hold 6 significant decimal digits. See godbolt.org/z/avbTW1Wcn for the output of the above program.
    – Wolf
    Commented May 25 at 9:53
3

to save a float number to a text file

Use "%e", "%g", "%a"

To print unique text for each float, use the format string "%.*e", "%.*g" or "%a" with sufficient precision.

FLT_DECIMAL_DIG - 1 is the number of digits needed with "%.*e"
(FLT_DECIMAL_DIG is the number of digits needed ,with "%.*g")
to print each float value uniquely without undue precision.

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

fprintf(fPointer, "%.*e", FLT_DECIMAL_DIG - 1, amount);
// or 
fprintf(fPointer, "%.*g", FLT_DECIMAL_DIG, amount);
// or 
fprintf(fPointer, "%a", amount); // Hexadecimal significand

What is nice about this is that the upper bound of characters needed can be pre-calculated if one wants to print to a string (typically about 18).

//                     -   d   .      dddddddd             e   -  expo \0
#defined FLT_STR_SIZE (1 + 1 + 1 + (FLT_DECIMAL_DIG - 1) + 1 + 1 + 4 + 1
char buffer[FLT_STR_SIZE];
snprintf(buffer, sizeof buffer, "%.*e", FLT_DECIMAL_DIG - 1, amount);

"%f" weaknesses

Using "%f" will print nearly half of small float like 0.000000001f and -1.2345e-10 as 0.000000 or -0.000000.

Using "%f" will print large float like FLT_MAX with verbose text like "340282346638528859811704183484516925440.000000".


OP's coding error's include:

// OP's code           v---- Format string expected here. 
// fprintf(fPointer, amount);
7
  • @Wolf Details added. Commented May 23 at 15:00
  • @Wolf 1) Answer amended to "%.*e". 2) "there has to be exactly one digit before the decimal point" is more like "there is one non-zero digit before the decimal point" 3) Definition of FLT_DECIMAL_DIG is in #include <float.h> as done in this answer. Commented May 24 at 12:12
  • BTW, it's not totally clear whether to user FLT_DECIMAL_DIG or FLT_DIG in this case.
    – Wolf
    Commented May 24 at 15:12
  • @Wolf Use FLT_DECIMAL_DIG to write distinctive text for all float finite values. FLT_DIG is insufficient. Commented May 24 at 16:16
  • 1
    IMO the answer was clearer before yesterday. The simple reason that the code in the question did not work was that it was missing the format string which is now buried at the bottom at the answer. All the details above about which format string to use are interesting, but distract from this simple fact.
    – mkrieger1
    Commented May 25 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.