If I do this:
void printfloat(float number)
{
printf("%f", number);
}
and
void printdouble(double number)
{
printf("%f", number);
}
What is the maximum number of characters that can be output by each function?
Via testing, using MS Visual Studio 10, a string of 811 resulted from
sprintf(buf, "%.*f", 500, -DBL_MAX);
Certainly longer strings are possible with larger precision values.
But staying with "%f", the maximum number of characters output is 317 + 1 for the '\0'.
So for portable code:
#include <float.h>
#include <stdio.h>
char buf[1/*'-'*/ + (DBL_MAX_10_EXP+1)/*308+1 digits*/ + 1/*'.'*/ + 6/*Default? precision*/ + 1/*\0*/];
sprintf(buf, "%f", -DBL_MAX);
The function printfloat(float number) lone parameter "number", being a float and limited to a float's range, is converted to a double in passing to sprintf(). It's maximum value is thus FLT_MAX. So the maximum number of characters output is 47 + 1 for the '\0'.
char buf[1/*'-'*/ + (FLT_MAX_10_EXP+1)/*38+1 digits*/ + 1/*'.'*/ + 6/*Default? precision*/ + 1/*\0*/];
sprintf(buf, "%f", -FLT_MAX);
Conclusion:
I was unable to get snprintf to tell me how big the string would be, and I want to keep the code as compiler-independent as possible. So here is the solution I came up with.
char numstr[50];
sprintf_s(numstr, "%g", *value);
m_stringRepresentation += numstr;
%g outputs the number in scientific notation, which severely limits the number of characters. I picked a buffer large enough to contain anything that might output. My only compiler-dependency is on sprintf_s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With