Does anyone know how to convert from a double type to string a string type?
I know I can use itoa() for integers, ltoa() for long values. but what about double?
Does anyone know how to convert from a double type to string a string type?
I know I can use itoa() for integers, ltoa() for long values. but what about double?
sprintf(), %f defaults to 6 decimal places %.4f use 4 places etc...
Code:double d = 123456.1234567899; char s[50]; sprintf(s,"%f", d); printf("%s\n", s); sprintf(s,"%.10f", d); printf("%s\n", s); sprintf(s,"%.2f", d); printf("%s\n", s);
Actually I believe that if you are converting a double then you should use:
sprintf(str,"%lf", yourdouble); /* and whatever precision spec's you want */
%f is for floats and %lf for doubles.
This is undefined behavior for pre-C99 implementations. See also Q15.2 and Q12.9. And since I've probably stirred the pot a little, I'll copy a quote from here:Originally posted by penney
Actually I believe that if you are converting a double then you should use:
sprintf(str,"%lf", yourdouble); /* and whatever precision spec's you want */
%f is for floats and %lf for doubles."%lf" in a format for printf() results in undefined behavior. The compiler may do anything with it and still be in compliance, including treating it exactly the same as "%f".
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
This is paste from the MS Visual C++ Type Field Characters page .
f = double
Signed value having the form [ – ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
g = double
Signed value printed in f or e format, whichever is more compact for the given value and precision. The e format is used only when the exponent of the value is less than –4 or greater than or equal to the precision argument. Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it.
G = double
Identical to the g format, except that E, rather than e, introduces the exponent (where appropriate).
No stirring of the pot here - I love to learn new things and I just learned somthing I never knew. It appears that sprintf accepts %f for doubles - which I didn't know but sscanf does not work that way and I have to use %lf to read into a double or specify a precision. At least that's what I'm seeing on my compiler. My little mind would have preferred that there was some consistency between the two forms of functions in that they could both use %lf. Although again on my compiler the %lf with sprintf doesn't seem to mind.