C++: What is the printf() format spec for float? (Visual C++)
It used to be that I used %g for float and %lg for double. 
It looks like the spec changed and float is undefined and double is %g.
I have bits in memory that I am printing out so casting is not an option.
Is there a way that I can print out float values using printf() ?
Update:
This code was written for unit testing generic C++ libs used on an embedded system. 
Here's what I had to do to get the float to work. 
The code is in a template function:
template <typename T,typename TTYP,typename Ttyp,int bits,bool IsSigned> 
Error testMatrixT() 
{ ...
Here is a code snip:
if (typeid(Ttyp) == typeid(float)) {    
    float64 c = *(float32*)&Tp(row,col);
    float64 a1 = *(float32*)&Arg1(row,col);
    float64 a2 = *(float32*)&Arg2(row,col);
    float64 e = *(float32*)&Exp(row,col);
    m_b = (c == e);
    _snprintf(m_acDiag, sizeof(m_acDiag)-1
        , "add(Arg1,Arg2): arg1=%g, arg2=%g, Expected=%g, Actual=%g, Result: %s"
        , a1, a2, e, c, BOOL_PF(m_b));
} else {
    ...
Pretty ugly isn't it? Using floats as args give bad output. Maybe due to using _snprintf() ?
Years ago I would use %lg and it would be OK. Not anymore.
So, you can see here that %d is used for integers, %f for floats and %c for characters. As simple as that! %. 2f means that the variable to be printed will be of type float and '.
%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].
double and float use the same format specifiers with printf (%a, %e, %f, and %g).  This is because printf is a variadic function.  Any float arguments are implicitly promoted to double before the call; you can't actually pass a float to printf.
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