Let's say I have:
f = ((100+x)/x)*1.5.
where f
is of type float
.
How can I convert it to a character string with a specified precision?
Let's say I have:
f = ((100+x)/x)*1.5.
where f
is of type float
.
How can I convert it to a character string with a specified precision?
How can I convert it to a character string with a specified precision?
There are 2 ways to consider precision for a double/float x
:
In an relative sense
int precision = 7;
// print to the 1+7 most significant digits
printf("%.*e\n", precision, x);
In an absolute sense
int precision = 7;
// print to the closest 0.0000001
printf("%.*f\n", precision, x);
Both have the issue of string/space management when printing to a string. Assuming a buffer that will not overflow, it is simple enough to use sprintf()
instead of printf()
.
int precision = 7;
// sign dig . precision e sign expo \0
char buf[1 + 1 + 1 + precision + 1 + 1 + 5 + 1];
// print to the 1+7 most significant digits
sprintf(buf, "%.*e", precision, x);
Using %f
is tricky as the number could be DBL_MAX
needing hundreds or thousands of digits.
int precision = 7;
// sign ------digs-------- . precision \0
char buf[1 + DBL_MAX_10_EXP + 1 + 1 + precision + 1];
// print to the closest 0.0000001
sprintf(buf, "%.*f", precision, x);
A classic approach is to use snprintf()
to compute the space needed by calling it once with 0
space and then determining the size needs. snprintf()
will not overfill the given size of the buffer. Still, snprintf()
results need to be checked to detect cases when the buffer was undersized.
int need = snprintf(NULL, 0, some_format, x);
assert(need >= 0);
char *buf = malloc(need + 1u);
assert(buf);
int need2 = snprintf(buf, need + 1u, same_format_as_before, x);
assert(need2 == need);
...
// do something with buf
...
free(buf);
Note: It is easy to mistakenly undersize a buffer's size considering extreme numbers and locale effects.
Note: Some code here assumes the exponent will not exceed 5 digits or 99999. A robust solution would right size as needed.
Always try to use Standard Library functions. Creating string from float, with precision, you can use sprintf.
Example:
#include <stdio.h>
#include <math.h>
int main()
{
char str[80];
sprintf(str, "Value of Pi = %f", M_PI);
return(0);
}
Use the snprintf to encode a float as a string and place it into a character buffer you provide. The second parameter is the size of the buffer to ensure that you don't overflow the space available. You also need to check the result of snprintf to ensure the string was created successfully without overflow.
#include <assert.h>
#include <stdio.h>
int main()
{
float number_as_float = 6.02;
char number_as_ascii[40];
assert(snprintf(number_as_ascii, 40, "%f", number_as_float) <= 40u);
return(0);
}
Use the sprintf
function.
float f = 100/3;
char *s = malloc(128);
sprintf(s, "%f", f);