Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the maximum numbers of characters output by sprintf when outputting float and double variables?

Tags:

c

printf

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?

like image 591
Almo Avatar asked Aug 29 '11 20:08

Almo


Video Answer


2 Answers

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);
like image 59
chux Avatar answered Oct 15 '22 09:10

chux


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.

like image 35
Almo Avatar answered Oct 15 '22 07:10

Almo