Convert float to string without losing precision

C99 supports the %a format in printf that allows to output the contents of a double without loss of precision.


That would depend upon whether your float value 23.345466467 is exactly representable (likely not)

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Why Floating-Point Numbers May Lose Precision

I would also question why you need to do this? What are you going to use the string representation for? Are you aware of the double and decimal types?

[Untested: you could try casting to double and then using "%d" Maybe this will pull in the extra 'guard' digits' but it still won't work for all values]


See the nice detailed discussion in http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/ .

The short answer is that the minimum precision is the following:

printf("%1.8e", d);  // Round-trippable float, always with an exponent
printf("%.9g", d);   // Round-trippable float, shortest possible
printf("%1.16e", d); // Round-trippable double, always with an exponent
printf("%.17g", d);  // Round-trippable double, shortest possible

Or equivalently, with a std::ostream& os:

os << scientific << setprecision(8) << d;    // float; always with an exponent
os << defaultfloat << setprecision(9) << d;  // float; shortest possible
os << scientific << setprecision(16) << d;   // double; always with an exponent
os << defaultfloat << setprecision(17) << d; // double; shortest possible