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);